使用 mod_rewrite 重定向?

发布于 2024-09-16 02:24:42 字数 581 浏览 4 评论 0原文

所以我有一个网页,根据这个参数search.php?state=AL查询一些数据。

我想做的是在我的 .htaccess 文件中编写一条规则,该规则将:

  1. website.com/state/AL 转换为 search.php?state =AL
  2. 如果用户明确请求 search.php?state=AL,则将其转换为 /state/AL

我使用以下命令完成了步骤 1:

RewriteRule ^state/([A-Za-z][A-Za-z]) /search.php?state=$1 [NC]

如何完成步骤 2?我知道我必须使用 [R, NC] 来实际重写 URL,但这就是我陷入困境的地方。

编辑:不确定这是否重要,但我的网络主机迫使我出于某种原因将 RewriteBase / 添加到我的 .htaccess 文件的顶部。

So I have a webpage that queries some data based on this parameter search.php?state=AL.

What I'm trying to do is write a rule in my .htaccess file that will:

  1. translate website.com/state/AL into search.php?state=AL
  2. If a user specifically request search.php?state=AL then translate that into /state/AL

I accomplished step 1 using this:

RewriteRule ^state/([A-Za-z][A-Za-z]) /search.php?state=$1 [NC]

How can I accomplish step 2? I know I will have to use [R, NC] to actually rewrite the URL, but thats where I'm stuck.

EDIT: Not sure if this matters but my webhost forces me form some reason to add RewriteBase / to the top of my .htaccess file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒与心事 2024-09-23 02:24:42

您只想在原始请求指向 /search.php?state= URL 的情况下执行重定向,如下所示:

RewriteEngine On

# Externally redirect /search.php?state=XX --> /state/XX
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/search\.php\?state=([A-Z]{2}) [NC]
RewriteRule ^ http://%{HTTP_HOST}/state/%1? [R=301,L]

# Internally redirect /state/XX --> /search.php?state=XX
RewriteRule ^state/([A-Z]{2}) /search.php?state=$1 [NC]

You want to perform the redirection only in the case that the original request was pointed to the /search.php?state= URL, like so:

RewriteEngine On

# Externally redirect /search.php?state=XX --> /state/XX
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/search\.php\?state=([A-Z]{2}) [NC]
RewriteRule ^ http://%{HTTP_HOST}/state/%1? [R=301,L]

# Internally redirect /state/XX --> /search.php?state=XX
RewriteRule ^state/([A-Z]{2}) /search.php?state=$1 [NC]
烟花易冷人易散 2024-09-23 02:24:42

像这样的事情就可以解决问题:

RewriteRule ^state/([A-Za-z][A-Za-z]) /search.php?state=$1 [NC, L]
RewriteCond %{QUERY_STRING} state=([A-Za-z][A-Za-z])
RewriteRule ^search\.php$ /state/%1 [R=303, NC]

Something like this would do the trick:

RewriteRule ^state/([A-Za-z][A-Za-z]) /search.php?state=$1 [NC, L]
RewriteCond %{QUERY_STRING} state=([A-Za-z][A-Za-z])
RewriteRule ^search\.php$ /state/%1 [R=303, NC]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文