htaccess Rewrite Rule

孤人 提交于 2019-12-08 04:00:07

问题


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 $



来源:https://stackoverflow.com/questions/6851549/htaccess-rewrite-rule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!