我已经为好的SEO网址设置了RewriteRule
。我已经在https://htaccess.madewithlove.be/上开发了它,它可以按预期工作。
但是当我在我的网站上实现它时,它不起作用,并且服务器崩溃。
RewriteEngine On
RewriteRule ^(.+?(?=/))/(.+?)/?$ index.php?a=$1&b=$2 [QSA,L]
RewriteRule ^(.+?)/?$ index.php?a=$1 [QSA,L]
RewriteRule ^/?$ index.php [NC,L]
我期望是:
[https://example.com/> https://example.com/index.php
[https://example.com/page> https://example.com/index.php?a=page
[https://example.com/page/categorie> https://example.com/index.php?a=page&b=categorie
您的规则将导致重写循环,因为第二条规则将与重写的URL路径匹配,即。 index.php
。
您可以简单地在现有重写之前添加一个例外:
RewriteRule ^index\.php$ - [L]
如果请求与/index.php
相匹配(在第一次重写之后,它就这样做了,然后停止处理。)>
和/或,使您的正则表达式更具限制性(无论如何还是建议这样做)。例如,而不是匹配任何东西,即。 .+
,仅匹配单词字符,例如。 \w+
。 (匹配a-z
,A-Z
,0-9
和_
)。等等。或者匹配除斜杠或点之外的任何内容,例如。 [^/.]+
。然后,您无需将子模式设置为非贪婪(以避免与可选的尾部斜杠匹配)。
UPDATE:
如果要提供其他静态资源,则可能需要执行文件系统检查,以确保正在重写的请求尚未映射到文件(或目录)。这是常见的惯例,但是,它相对昂贵(就处理而言),并且通常可以通过使正则表达式更具限制性来避免-如上所述。例如:
RewriteEngine On
# Ignore (rewritten) requests for index.php
RewriteRule ^index\.php$ - [L]
# Ignore requests that map to files or directories
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# Rewrite pretty URLs
RewriteRule ^(\w+)/(\w+)/?$ index.php?a=$1&b=$2 [QSA,L]
RewriteRule ^(\w+)/?$ index.php?a=$1 [QSA,L]
RewriteRule ^/?$ index.php [NC,L]