You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenBSD的httpd.conf中移除URL的.html和.php后缀

OpenBSD httpd 同时移除.html和.php后缀的配置方案

完整可行配置

替换你当前httpd.conf中的location规则部分,使用以下配置:

server "example.com" {
    listen on * tls port 443
    root "/htdocs/example.com"
    hsts
    # 同时支持PHP和HTML首页
    directory index index.html index.php
    tls {
        certificate "/etc/ssl/mycert.pem"
        key "/etc/ssl/private/mykey.key"
    }

    # 外部重定向:将带.php的URL跳转到无后缀版本(301永久重定向)
    location match "^/(.*)\.php$" {
        request rewrite "/%1" permanent
    }

    # 外部重定向:将带.html的URL跳转到无后缀版本
    location match "^/(.*)\.html$" {
        request rewrite "/%1" permanent
    }

    # 内部映射:优先检查对应PHP文件是否存在,存在则转发给php-fpm
    location match "^/(.*)$" {
        fastcgi socket "/run/php-fpm.sock" if file exists "%h/%1.php"
    }

    # 内部映射:PHP文件不存在时,检查对应HTML文件是否存在
    location match "^/(.*)$" {
        request rewrite "/%1.html" if file exists "%h/%1.html"
    }

    # 保留直接访问.php的兼容规则
    location "/*.php" {
        fastcgi socket "/run/php-fpm.sock"
    }
}

配置逻辑说明

  1. 外部重定向:和你之前Apache的规则对应,强制将用户访问的file.php/file.html跳转到file,避免重复内容,同时保持URL整洁。
  2. 内部映射优先级:OpenBSD httpd按从上到下顺序匹配规则,所以先检查PHP文件,避免PHP请求被后续的HTML规则拦截导致404。
  3. 文件存在检查:通过if file exists确保只对实际存在的文件做映射,避免无效请求的错误转发。
  4. 首页支持:修改directory index加入index.php,保证访问根目录时能识别PHP首页。

你之前无效配置的问题分析

  • 第一种配置:匹配的是带后缀的URL,重写后还是原路径,完全没有实现"移除后缀"的逻辑,属于方向错误。
  • 第二种配置:使用了错误的正则语法%w+,OpenBSD httpd采用POSIX扩展正则,应该用[a-zA-Z0-9_]+表示单词字符,语法错误导致匹配失败。
  • 第三种配置:只做了外部重定向(带后缀转无后缀),但没有处理内部映射(无后缀请求转实际文件),且没有设置优先级,导致PHP请求找不到对应文件。

生效步骤

修改配置后执行:

rcctl restart httpd

测试场景:

  • 访问https://example.com/test.php → 自动跳转到https://example.com/test并正常显示PHP内容
  • 访问https://example.com/test.html → 自动跳转到https://example.com/test并正常显示HTML内容
  • 直接访问https://example.com/test → 优先加载test.php,不存在则加载test.html,都不存在返回404

内容的提问来源于stack exchange,提问作者gold_member

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 03:51:13