【问题标题】:Nginx: How to rewrite all URLs except of images?Nginx:如何重写除图像之外的所有 URL?
【发布时间】:2011-11-15 11:35:47
【问题描述】:

我是 nginx 新手,我想将我的网站从 Apache 迁移到 nginx。我的网站有如下网址:

www.mywebsite.com/category/product/balloon
www.mywebsite.com/category/product/shoe
www.mywebsite.com/information/help
等等

由于我使用的是 PHP,我需要将所有 URL 重写为 index.php,除非它是图像或“假请求”。到目前为止我的 nginx.config:

    #block fake requests
    location ~* \.(aspx|jsp|cgi)$ {
        return 410;
    }

    #rewrite all requests if it's not a image
    location / {
        root   html; 
        index  index.php 500.html;

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

    error_page  404 /index.php;

    # serve static files directly
    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
        access_log        off;
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }               

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  E:/test2/html/$fastcgi_script_name;
        include        fastcgi_params;
    }

此配置不起作用,因为:
1. 它不会阻止对 .php 文件的虚假请求,我无法将 .php 添加到 (aspx|jsp|cgi)$
2. 如果文件存在错误,它不会重写 URL:它应该只直接提供静态文件
    如果它是在 (jpg|jpeg|gif|css|png|js|ico) 中定义的文件类型$

我该如何解决这些问题?我非常感谢您能给我的每一个答案、澄清或反馈。

谢谢 迈克

【问题讨论】:

    标签: regex nginx fastcgi url-rewriting


    【解决方案1】:

    您需要配置 HttpRewriteModule。该模块可以使用正则表达式 (PCRE) 更改 URI,并根据变量重定向和选择配置。

    如果此模块的指令是在服务器级别给出的,那么它们会在确定请求的位置之前执行。如果在该选定位置有进一步的重写指令,那么它们也会被执行。如果 URI 由于在 location 内执行指令而发生更改,则再次确定新 URI 的位置。

    【讨论】:

    • 您好 Roland,感谢您的回答。你能给我一个代码示例吗?
    猜你喜欢
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多