mod_rewrite 条件的基本帮助

发布于 2024-11-18 12:43:01 字数 298 浏览 2 评论 0原文

你好。我是 mod_rewrite 的新手,想知道是否可以执行以下操作:

RewriteRule ^([^/]*)$ index.php?slug=$1

此规则仅指向 index.php 但如果我想做另一条规则,将特定的 slug 指向不同的脚本,即

RewriteRule ^a-new-page$ different.php

这将不起作用,因为第一条规则声明输入的任何内容都应指向索引。

有没有办法对特定的蛞蝓强制执行新规则?

Hi. I am new to mod_rewrite and was wondering if it was possible to do the following:

RewriteRule ^([^/]*)$ index.php?slug=$1

This rule will point only at index.php but if I wanted to do another rule that pointed a specific slug to a different script, i.e.

RewriteRule ^a-new-page$ different.php

This would not work because the first rule has declared anything that is entered should point at index.

Is there a way to force the new rule for that specific slug?

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

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

发布评论

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

评论(1

梦情居士 2024-11-25 12:43:01

是的,这是可能的——只需将此类特定规则放在通用/广义规则之前(规则声明的顺序很重要):

RewriteRule ^a-new-page$ different.php
RewriteRule ^([^/]*)$ index.php?slug=$1

另请注意广义规则——它们可能会进入一个重写循环(重写新 URL 后进入下一次迭代,如果规则编写不正确,可能会进入无限循环,Apache 将不得不强制终止,您的用户将看到 500 错误页面)。更好的规则是:

# specific rule
RewriteRule ^a-new-page$ different.php [L,QSA]

# broad rule (will be triggered if requested resource is not a file or directory) 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)$ index.php?slug=$1 [L,QSA]
  • 如果此规则匹配,[L] 告诉 Apache 停止重写
  • [QSA] 告诉将查询字符串附加到新 URL(如果您有 URL 参数,则很有用) :例如跟踪数据、页面参数等)。

有用的链接:http://httpd.apache.org/docs/current/rewrite/

Yes, it is possible -- just place such specific rule before generic/broad one (the order in which rules are declared matters):

RewriteRule ^a-new-page$ different.php
RewriteRule ^([^/]*)$ index.php?slug=$1

Also please pay attention to the broad rules -- they may enter into a rewrite loop (after rewrite new URL goes into next iteration, and if rule is not written right it may enter endless loop which Apache will have to forcedly terminate and your user will see an 500 error page instead). Better rule will be:

# specific rule
RewriteRule ^a-new-page$ different.php [L,QSA]

# broad rule (will be triggered if requested resource is not a file or directory) 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)$ index.php?slug=$1 [L,QSA]
  • [L] tells Apache to stop rewriting if this rule matches
  • [QSA] tells to append query string to a new URL (useful if you have URL parameters: e.g. tracking data, page parameters etc).

Useful Link: http://httpd.apache.org/docs/current/rewrite/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文