这可能更多是一个正则表达式问题,或者可能是一个httpd.conf,但我认为我已经非常接近了。只是需要一点帮助。让我说,我总是在正则表达式上挣扎,尽管有这样的网站:https://regex101.com。
我需要通过删除 .html 和 .php 来重写 URL 的帮助。在我的网络服务器中,我有一些 HTML 页面和一个 PHP 页面。
在我之前的 Web 服务器 Apache 中,我的 .htaccess 文件中列出了以下内容,并且它运行良好。
RewriteEngine On
RewriteBase /
# **PHP Files** - Redirect file.php to file
RewriteCond %{THE_REQUEST} \s/([^.]+)\.php [NC]
RewriteRule ^ /%1 [NE,L,R]
# Internal map file.php to file
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php [L]
# **HTML Files** - Redirect file.html to file
RewriteCond %{THE_REQUEST} \s/([^.]+)\.html [NC]
RewriteRule ^ /%1 [NE,L,R]
# Internal map file.html to file
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)/?$ /$1.html [L]
我会这样引用网址:www.example.com/about或www.example.com/contact-us(我的ahref中没有给出.html或.php扩展名),它会重写 URL,不带扩展名。
在我的新网络服务器下,我的 httpd.conf 配置如下:
server "example.com" {
listen on * tls port 443
root "/htdocs/example.com"
hsts
directory index index.html
tls {
certificate "/etc/ssl/mycert.pem"
key "/etc/ssl/private/mykey.key"
}
location "/*.php" {
fastcgi socket "/run/php-fpm.sock"
}
location "/*.php*" {
fastcgi socket "/run/php-fpm.sock"
}
# Remove .html extension
location match "/([^.]+)$" {
request rewrite "/%1.html"
}
}
最后一个以粗体突出显示的“位置匹配”将我的所有 .html 重写为没有扩展名的文件。对于所有 HTML 页面,它都能按预期工作。然而,我拥有的一个 PHP 页面显然不起作用。我收到 404 错误,因为服务器需要 contactus.html,但有 contactus.php。
我需要一个正则表达式,这样当 URL 为 https://example.com/contactus.php 时,它会将其重写为 https://example.com/contactus。
我尝试了以下方法,但似乎没有任何效果:
location match "/([^.]+)\.html$" {
request rewrite "/%1.html"
}
location match "/([^.]+)\.php$" {
request rewrite "/%1.php"
}
location match "/(%w+).html$" {
request rewrite "/%1.html"
}
location match "/(%w+).php$" {
request rewrite "/%1.php"
}
注意:OpenBSD 有一个关于模式的文档,因此是 %w。参考:https://man.openbsd.org/patterns.7
location match "^/(.*)(\.html)$" {
request rewrite "/$1"
}
location match "^/(.*)(\.php)$" {
request rewrite "/$1"
}
我已阅读这些页面:
还有大量的谷歌搜索,但我的服务器无法同时使用两者。
请注意,每次更改配置文件后,我都会重新启动httpd服务:
rcctl restart httpd
我可以使用特定的正则表达式来处理这两种页面类型吗?
谢谢!
我想我已经明白了。至少,以下内容对我有用。我不确定是否有更好的解决方案或者更有效的解决方案,但我想我分享了到目前为止我所拥有的。
location "/contact-us" {
request rewrite "/contact-us.php"
}
location match "/([^.]+)$" {
request rewrite "/%1.html"
}
这里的顺序很重要。如果点击特定页面(在本例中为“联系我们”页面),它将重写为 contact-us.php。否则,对于其他所有内容,它将使用 .html 扩展名重写。正则表达式末尾的 $ 符号非常重要,因此此重写不会拾取 css、js 和图像文件。
如果有人知道如何将第一个块从 location "/contact-us" 更改为 location match (<some_regex>.php) 这样我就不必对各个 PHP 页面进行硬编码,我会感谢您的帮助。