开发者

.htaccess mod_rewrite remove .php extension, but preserve URL path

I currently have PHP scripts that work properly, being called like this: www.example.com/user.php/paul and www.example.com/tag.php/food

I'm having trouble getting .htaccess to rewrite properly. I'm trying to achieve this: www.example.com/user/paul www.example.com/tag/food

So far, I can get it to redirect /user to /user.php, but the /paul is lost; breaking my script.

My current .htaccess looks like this:

RewriteEngine On
RewriteCon开发者_开发问答d %{THE_REQUEST} ^GET\ /([^.\ ]+\.)+php(\?[^\ ]*)?\ HTTP
RewriteRule ^(.+)\.php$ http://www.example.com/$1 [R=301,L]
RewriteRule ^([^/]+/)*index/?$ http://www.example.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ http://www.example.com/$1 [R=301,L]
RewriteCond $1 !^([^.]+\.)+([a-z0-9]+)$ [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*[^/])$ /$1.php [L]

Please help. Thanks! Paul


You probably should be using a rule like this somewhere:

RewriteRule ^/([^/]*)/([^/]*)$ /$1.php/$2

Here's it again, in English.

First comes the beginning of the path                        ^/
The first component of the path doesn't have / symbols in it [^/]*
We remember it                                               ()
Then comes the slash between the components                  /
Then the second component without the / symbols              [^/]*
Remember it too                                              ()
And the path ends                                            $

Replace it with the first remembered things followed by .php/ followed by the second remembered thing.

You probably don't want to use [L] in this rule, the redirect is not necessary, the user doesn't need to know that your scripts really have a .php suffix.

Hope this is correct, I cannot check it on a working Apache right now.


Put this code in your .htaccess file:

Options +FollowSymlinks -MultiViews
RewriteEngine on

# external redirect to hide .php
RewriteCond %{THE_REQUEST} ^GET\s.+\.php [NC]
RewriteRule ^([^/]+)\.php/(.*)$ /$1/$2 [NE,R=301,L,NC]

# internal redirect to add .php
RewriteRule ^([^/]+)(?<!\.php)/(.*)$ /$1.php/$2 [L]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜