htaccess external rewrite / internal redirect

寵の児 提交于 2019-12-22 08:29:25

问题


There are two things that I would like to achieve with .htaccess file. The first one is

www.hostname.com/index.php?question  -> www.hostname.com/question
www.hostname.com/index.php?myinfo  -> www.hostname.com/myinfo
www.hostname.com/index.php?notification  -> www.hostname.com/notification

so I use external rewrite to re-express on the URL as following.

RewriteCond %{THE_REQUEST} /(index.php)\?([^&]+)\ HTTP
RewriteRule ^ /%2? [R=301,L]

Now the above statement correctly displays as I want. The problem is to internally convert back when a condition is satisfied. The condition is if %{THE_REQUEST} is equal to any character after '/'.

RewriteCond %{REQUEST_URI} ^/(.*)$ [NC]
RewriteRule ^(.*)$ index.php?$1 [NC,L]

So that my php code can recognize the $_GET parameter. Here, even though the condition is satisfied it will not process the RewriteRule.

The second problem is

www.hostname.com/index.php?category=spo  -> www.hostname.com/category/spo
www.hostname.com/index.php?category=ite  -> www.hostname.com/category/ite
www.hostname.com/index.php?category=gam  -> www.hostname.com/category/gam

The conversion is completed using exteral rewrite:

RewriteCond %{THE_REQUEST} /(index)\?category=([^&]+)\ HTTP
RewriteRule ^ category/%2? [R=301,L]

Again, I'd like to convert back whatever is written in the URL back to the original format internally so I use the following condition to differentiate from the previous case,

RewriteCond %{REQUEST_URI} ^/category/(.*)$
RewriteRule ^category/(.*)/?$ index.php?category=$1 [NC,L]

my php code cannot recognize the $_GET parameter and variable. When I use htacces tester, it says it should work but it doesn't. http://martinmelin.se/rewrite-rule-tester/

How do I fix this problem? OR is there any easier way to accomplish this?

Thank you


回答1:


Try these rules:

RewriteEngine On

RewriteCond %{THE_REQUEST} \s/index\.php\?category=([^&\s]+) [NC]
RewriteRule ^ /category/%1? [R=301,L]

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

RewriteCond %{THE_REQUEST} \s/index\.php\?([^&\s]+) [NC]
RewriteRule ^ /%1? [R=301,L]

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


来源:https://stackoverflow.com/questions/21210606/htaccess-external-rewrite-internal-redirect

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