【问题标题】:Nginx: Question mark in front controller rewrite ruleNginx:前端控制器重写规则中的问号
【发布时间】:2012-10-17 15:23:01
【问题描述】:

目前我有这段代码:

if (!-e $request_filename)
{
    rewrite ^/(.*)$ /index.php?/$1 last;
    break;
}

这适用于以下情况: example.com/foo 重定向到 index.php

但是example.com/foo?bar 不起作用。你是如何让它发挥作用的?

FWIW:我在 Apache 的 mod_rewrite 等效项中没有遇到这个问题。基本上,我将一个可以工作的站点从 Apache 转移到 Nginx。现在我遇到了这个问题。

编辑:

要清楚这是我要做的事情:

  • example.com/foo
  • example.com/foo/bar/etc
  • example.com/foo?bar
  • example.com/foo?bar=quz

应该全部“静默”地提供index.php,而不更改浏览器地址栏的URL。

【问题讨论】:

    标签: php mod-rewrite url-rewriting nginx rewrite


    【解决方案1】:

    我刚刚使用以下配置对其进行了测试,我相信这确实需要您想要的:

    server {
    #listen   80; ## listen for ipv4; this line is default and implied
    #listen   [::]:80 default ipv6only=on; ## listen for ipv6
    
    root /home/www/test;
    index index.php index.html index.htm;
    
    # Make site accessible from 
    server_name test.myhost.nl;
    
    location / {        
        # First attempt to serve request as file, then as directory, then fall back to index.php
        try_files $uri $uri/ /index.php?$args;
    }
    
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
        try_files $uri = 404;
    
        # Fix for server variables that behave differently under nginx/php-fpm than typically expected
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # Include the standard fastcgi_params file included with ngingx
        include fastcgi_params;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_index index.php;
    
        # Override the SCRIPT_FILENAME variable set by fastcgi_params
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    
        # Pass to upstream PHP-FPM; This must match whater you name your upstream connection
        #fastcgi_pass phpfpm;
        fastcgi_pass 127.0.0.1:9000;
    }
    }
    

    【讨论】:

    • 我试过了,但它不起作用,它提示下载 PHP 文件。这是我的完整代码:pastebin.com/3Nhhbu5D
    • 嗯,在 pastebin 代码中,您在 try_files 之后缺少 ;。如果这不是问题,请尝试在您的 php 位置块之外添加以下块:location / { try_files $uri $uri/ /index.php?$args; } 我也不建议使用 if 语句来重定向 www 部分,您可以为 www.yourhost.com 使用不同的服务器块重定向到 yourhost.com。
    • 对丢失的; 感到抱歉。这是更新的代码:pastebin.com/yGKZYGqu。现在example.com/foo 不会被重定向到index.php
    • 好的,如果你把location /块放在php块上面呢?如果您输入 example.com/foo.php 会发生什么情况会被重定向?
    • 如果/ 块被移动,也会发生同样的事情。 /foo.php get 直接重定向到 index.php,地址栏中的 URL 显示为 example.com/index.php。请注意,在我上面的原始代码中,example.com/foo 将在内部重定向到index.php,而example.com/foo 仍保留在地址栏中,这是我想要的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多