htaccess rewrite from page ID to name not working

2019-08-15 05:17发布

I'm calling ?page=about using the GET method in a form on index.php (ie. 'about' is a select option). Once I click submit, the URL will look like this:

http://example.com/?page=about

However I would like it to look like this instead:

http://example.com/about

but keep the script (PHP) working on index.php (do don't and don't want to have an 'about' file), ie. I would like to make use of the GET values on the same page once the form is sent. I can make the php script work, it reacts fine, but the URL rewriting does not work at all.

I have tried the following htaccess rewrite, but it doesn't do anything, the URL remains as above.

My htaccess:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ?page=$1 [L,QSA]

I would greatly appreciate your help, as I have no idea why this isn't working. I have searched through the net, and everyone points to this rule, yet it just doesn't do any thing at all for me.

Thanks a lot in advance!

EDIT:

Let me post my php code I use, sorry, I missed that. I have removed the action attribute for now as I'm using it in a browser that I know is sending me to the same when submitting the form:

<?php

$page = $_GET['page'];

switch($page){
 case 'about': echo 'I am me'; break;
 case 'galery': echo 'Nice pictures here'; break;
}

?>

<body>

<form action="/" method="get">
<select name="page">
    <option value="about">about</option>
    <option value="galery">galery</option>
</select>
<input type="submit" value="Submit" />
</form>
</body>

EDIT #2:

I had to add action="/" to the form tag in order anubhava's solution to work.

2条回答
Ridiculous、
2楼-- · 2019-08-15 05:42

Try

 ...
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]

And

I'm calling ?page=about using the GET method in a form on index.php

Try calling the right link? '/about' instead of '?page=about'

查看更多
乱世女痞
3楼-- · 2019-08-15 05:43

This should be your complete .htaccess:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

#external redirect from /?page=about OR /index.php?page=about to /about
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(?:index\.php|)\?page=([^\s]+) [NC]
RewriteRule ^ /%1? [R=301,L]

#internal forward from /about to /?page=about
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+?)/?$ /?page=$1 [L,QSA]
查看更多
登录 后发表回答