Apache - 需要将 /contact/ 重写为 /contact.php

Pol*_*a18 4 mod-rewrite .htaccess apache-2.4

使用.htaccess之前的问题,我对其进行了编辑以添加重写规则以重写/contact/to/contact.php/xyz/contact/to /contact.php?lang=xyz。当第二个工作时,第一个仍然寻找不存在的实际目录,返回404代码。两个重定向到漂亮的 URL 变体都按预期工作。这是我的.htaccess设置:

# No directory listing, no multi views, follow symlinks
Options -Indexes -MultiViews +FollowSymLinks

# Redirects and rewrites allowed
RewriteEngine on

# ...

# Redirect direct requests for "contact.php?lang=xyz" to "/xyz/contact/"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^lang=([a-z]{2,3})$
RewriteRule ^contact\.php$ /%1/contact/? [R=301,L]

# Redirect direct request for "contact.php" to "/contact/"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^contact\.php$ /contact/? [R=301,L]

# Internally rewrite "/xyz/contact/" to "/contact.php?lang=xyz"
RewriteRule ^([a-z]{2,3})/contact/?$ /contact.php?lang=$1 [L]

# ...

# Internally rewrite "/contact/" to "/contact.php"
RewriteRule ^/contact/?$ /contact.php [L]
Run Code Online (Sandbox Code Playgroud)

MrW*_*ite 7

# Internally rewrite "/contact/" to "/contact.php"
RewriteRule ^/contact/?$ /contact.php [L]
Run Code Online (Sandbox Code Playgroud)

在每个目录的.htaccess文件中,您需要删除RewriteRule 模式上的斜杠前缀(就像您在前面的指令中所做的那样)。所以这应该写成:

RewriteRule ^contact/?$ /contact.php [L]
Run Code Online (Sandbox Code Playgroud)

这匹配/contact和 的请求/contact/

RewriteRule 模式中不使用斜杠前缀,因为在.htaccess上下文中,目录前缀(特别以斜杠结尾)首先从RewriteRule 模式匹配的 URL 路径中删除。(目录前缀是文件所在位置的.htaccess文件系统路径。)