htaccess Rewrite Rule

2019-05-31 19:26发布

问题:

I use htaccess to rewrite my URL's so here is what I have:

RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?page=$1 [L]

So if I go to domain.com/services then it works perfect, but what I want to do is make it so if they do type in domain.com/services.php then it will work instead of not being found.

Also.. if I go to domain.com/services/ (with a trailing slash) then it acts like it's not found. Why is this?

回答1:

You have limited "rewrite loop" (limited to 2 iterations only). Use these rules:

# do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]

RewriteRule ^([a-z0-9_\-]+)(\.php)?$ index.php?page=$1 [NC,L,QSA]

If you do not like it, here is an alternative (but I still prefer #1, but maybe this one will be better for your setup/app logic -- this assumes that index.php is located in website root folder):

RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^([a-z0-9_\-]+)(\.php)?$ index.php?page=$1 [NC,L,QSA]


回答2:

For the second requirement (the php extension) try this

RewriteRule ^([a-zA-Z0-9_-]+)(\.php)?$ index.php?page=$1 [L]

untested, but it should work.



回答3:

RewriteRule ^([a-zA-Z0-9_-]+)\.php$ index.php?page=$1 [L]
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?page=$1 [L]
RewriteRule ^([a-zA-Z0-9_-]+)\/$ index.php?page=$1 [L]

add slash as aceptable possible character (note ^([a-zA-Z0-9_-]+)\/$)



回答4:

This should work for you:

RewriteRule ^([a-zA-Z0-9_-]+) index.php?page=$1 [L]

You aren't allowing a period, so the '.php' fails the expression since it is terminated with $