【问题标题】:URL with Rewrite in Nginx在 Nginx 中重写的 URL
【发布时间】:2022-01-25 04:29:15
【问题描述】:

我希望 URL 在重写后看起来干净漂亮。我在使用 Apache 时能够做到这一点,但我在服务器上安装了 Nginx。所以我不使用.htaccess

在使用 Apache 时,我是这样使用它的:

<IfModule mod_rewrite.c> 
    SetEnv HTTP_MOD_REWRITE On
    RewriteEngine on 
    RewriteBase / 
    RewriteCond %{REQUEST_URI} !\.php$ [NC] 
    RewriteCond %{REQUEST_URI} [^/]$ 
    RewriteRule ^(.*)$ $1.php [L] 
    RewriteCond %{REQUEST_FILENAME} -d [OR] 
    RewriteCond %{REQUEST_FILENAME} -f [OR] 
    RewriteCond %{REQUEST_FILENAME} -l
    RewriteCond %{REQUEST_URI} !.(css|gif|ico|jpg|js|png|swf|txt)$ 
    RewriteRule ^ - [L] 
     RewriteRule ^([^/]+)/([^/]+)?$ index.php?cmd=$1&scd=$2 [L,QSA] 
    RewriteRule ^([^/]+)/?$ index.php?cmd=$1 [L,QSA]
</IfModule>

此 URL 示例如下所示:

https://example.com/item/1234/bund123

没有 mod_rewrite:

https://example.com/index.php?item?id=1234&unt=bund123

我尝试使用 Nginx 进行此操作,但出现 404 错误。这可能是什么原因?

server {

    listen *:80;
        listen [::]:80;
        listen *:443 ssl http2;
        server_name example.com www.example.com;
        root   /var/www/example.com/web/;

        rewrite ^([^/]+)/([^/]+)?$ /index.php?cmd=$1&scd=$2 last;
        rewrite ^([^/]+)?$ /index.php?cmd=$1 last;
 
    ....
}

我哪里做错了?

【问题讨论】:

    标签: .htaccess nginx mod-rewrite url-rewriting


    【解决方案1】:

    有关 404 错误的详细信息可以在 Nginx 错误日志中找到。想必index.php是不存在的。

    可以使用redirect 和Curl 快速测试重写规则:

    # /item/cmd/scd
    rewrite ^/item/([^/]+)/([^/]+) /index.php?cmd=$1&scd=$2 redirect;
    
    # /item/cmd
    rewrite ^/item/([^/]+)         /index.php?cmd=$1        redirect;
    
    $ curl -I https://example.com/item/CMD/SCD
    HTTP/1.1 302 Moved Temporarily
    Location: https://example.com/index.php?cmd=CMD&scd=SCD
    
    $ curl -I https://example.com/item/CMD
    HTTP/1.1 302 Moved Temporarily
    Location: https://example.com/index.php?cmd=CMD
    

    当重写工作正常时,将redirect 更改为break

    rewrite ^/item/([^/]+)/([^/]+) /index.php?cmd=$1&scd=$2 break;
    rewrite ^/item/([^/]+)         /index.php?cmd=$1        break;
    

    【讨论】:

    • 网站上有很多页面。其中之一是item。我正在使用item 页面显示对象的详细信息。我尝试了您的方法,但遇到了 404 错误:https://example.com/item/objectID - 我收到了 403 错误:https://example.com/index.php?cmd=item&amp;scd=objectID 我做错了什么吗? -- All Conf. Content
    • 如果以rewrite ^/item/(..开头,不影响其他页面吗?比如分类展示页面、联系人……CMD是页面名称
    • CMD: 页面 - SCD: 选项参数(类别 ID,项目 ID..)
    • 抱歉,404 卡在另一个选项卡中。我把它弄混了,我的错。我只是收到一个 403 错误。配置文件中的所有代码都属于 ISPconfig。我刚刚在页面下方添加了您的代码。
    • 感谢您的帮助。我注意到由于 PHP 版本的不同,您遇到了 403 错误,我已修复它。
    猜你喜欢
    • 2013-03-15
    • 1970-01-01
    • 2023-03-08
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2018-06-21
    相关资源
    最近更新 更多