.htaccess redirect from GET variable to url string

霸气de小男生 提交于 2019-12-12 08:01:23

问题


I need to redirect

/search?keywords=somesearchterm

to

/search/somesearchterm

This seems incredibly basic but I've been pounding my head against it for an hour.

Thanks for taking the time to look at this.


回答1:


You want to implement what is called a "301 Redirect" with mod_rewrite.

RewriteEngine ON
RewriteRule ^/search\?keywords=somesearchterm$ /search/somesearchterm

adding regular expressions:

RewriteEngine ON
RewriteRule ^/search\?keywords=(.+) /search/$1 [R=301,L]

R=301 means provide a 301 Header redirect so the user's URL changes in the browser, and L means don't process any more rewrite rules if this one matches.


If you want to do the reverse -- in other words, if someone goes to mysite.com/search/asearchterm and you want the URL to stay the same, but "behind the scenes" you want it to load a certain server script, do this:

RewriteEngine ON
RewriteRule ^/search/(.+) /search.php\?keywords=$1 [L]



回答2:


You can not match aginst Query string in RewriteRule directive. Use %{THE_REQUEST} or %{QUERY_STRING} server variables to match the Query string :

The following rule works fine for this redirection

 RewriteEngine On
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/search\?kewords=([^&\s]+) [NC]
 RewriteRule ^ /search/%1? [NE,NC,R,L]

RewriteRule ^search/([^/]+)/?$ /search?keyword=$1 [QSA,NC,L]


来源:https://stackoverflow.com/questions/3539522/htaccess-redirect-from-get-variable-to-url-string

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