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

Nginx等价重写规则无法正常工作,请求协助转换并调试Apache mod_rewrite规则

Nginx等价重写规则无法正常工作,请求协助转换并调试Apache mod_rewrite规则

各位好,我最近在把网站从Apache迁移到Nginx,需要把原来的.htaccess重写规则转换成Nginx的配置,但折腾了半天,部分规则好像没正常生效,实在搞不定了,来请教下大家!

先给大家看看我原来的Apache mod_rewrite(.htaccess)规则:

Options All -Indexes

RewriteEngine On
RewriteBase /

# 把结尾带斜杠的非文件/目录请求301跳转到index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ index.php [R=301,L]

# 处理posts相关的请求
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^posts/?$ post.php [QSA,NC,L]
RewriteRule ^posts/([^/]*)?$ post.php?title=$1 [QSA,NC,L]

这个Apache规则的主要作用是:

  • 禁止目录索引
  • 如果请求的不是真实文件或目录,且URL是以/xxx/结尾的,就301重定向到index.php
  • 访问/posts或/posts/时,转发到post.php;访问/posts/xxx时,把xxx作为title参数传递给post.php,同时保留原查询参数

然后是我自己尝试转换的Nginx配置:

server {
    listen       3000;
    server_name  localhost;

    root   c:/www;

    location / {
        index  index.php;
    }

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:7000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    location ~ "^/([^/]+)/$" {
        try_files $uri $uri/ /index.php$is_args$args;
    }
    location ~ "^/posts/?$" {
        try_files $uri $uri/ /post.php$is_args$args;
    }
    rewrite ^/posts/([^/]*)?$ /post.php?title=$1 last;
}

现在的问题是,原来Apache下正常的跳转和转发,在Nginx里要么没反应,要么参数传递不对。比如访问/test/的时候,没有像预期那样301重定向到index.php;访问/posts/test-title时,post.php好像拿不到title参数。

麻烦大家帮我看看哪里错了?有没有正确的转换方式,或者需要调整的地方?谢谢各位!

备注:内容来源于stack exchange,提问作者Alix Blaine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 09:59:38