Redirect and rewrite with mod_rewrite

旧时模样 提交于 2019-12-20 03:50:11

问题


After asking this question: Clean URLs for search query? I tried something with mod_rewrite:

RewriteCond %{QUERY_STRING} ^s=([a-z]+)$ [NC]
RewriteRule / /s/$1? [NC,R=301,L]

RewriteRule ^s/([a-z]+)$ /?s=$1 [NC,L]

What's the goal?

  1. Redirect http://example.com/?s=query to http://example.com/s/query
  2. Rewrite http://example.com/s/query to http://example.com/?s=query

This looks like double work but if you take a good look you see what I try to accomplish:

  1. Redirect any search querystring to a cleaner equivalent (be it a form, or somebody typing it in directly)
  2. Rewrite (not redirect) that URL back to dynamic querystring so that I can get it with PHP via $_GET

If I think about it like this it should be possible. So I would like to seek the help of the experienced mod rewriter to help me out with this one.

Number 2 works but that's it.


回答1:


This should work, I tested it with some different names and dirs, but that should be ok in your case.

NB: for matched group from the RewriteCond you must use %1 not $1.

RewriteCond %{QUERY_STRING} ^s=([a-z]+)$ [NC]        
RewriteRule ^$ /s/%1? [NC,R,L]                     

RewriteRule ^s/([a-z]+)$ /?s=$1 [NC,L] 

Edit for debug (see comments) :

my test is :

| /
| --> doc
|   |
|   --> doc.php (takes doc as GET parameter)
|     | index.php

My apache rewrite is

RewriteCond %{QUERY_STRING} ^doc=([a-z]+)$ [NC]
RewriteRule ^$ /doc/%1? [NC,R,L]

RewriteRule ^doc/([a-z]+)$ /doc/doc.php?doc=$1 [NC,L]

Then asking for domain.com/?doc=query displays doc is query

Works for me.



来源:https://stackoverflow.com/questions/5466166/redirect-and-rewrite-with-mod-rewrite

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