regex - Nginx:如何重写除图像以外的所有 URL?

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

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 )$

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

谢谢 迈克

最佳答案

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

如果此模块的指令是在服务器级别给出的,那么它们将在确定请求位置之前执行。如果在该选定位置中还有其他重写指令,则它们也会被执行。如果 URI 因在 location 内执行指令而更改,则将再次确定新 URI 的位置。

https://stackoverflow.com/questions/7390694/

相关文章:

python - 如何在 setup.py 中为 cython 设置 sysroot

spring - 无法从 InputStream : Invalid Content-Type:te

python - os.walk 某些文件类型到现有的 ZipFile?

sql-server - 从游标源 SQL Server 中删除行

maven-2 - 来自另一个模块的 Maven 模块属性

msbuild - 如何转储从 MSBuild 导入的属性表列表

maven-2 - Maven : Could not transfer artifact Erro

jsf - 如何注入(inject)不同的子类作为 ManagedProperty JSF 2?

xml - Spring:java.util.Locale 类型的 bean 的 Autowirin

python - 在 Matplotlib 中设置颜色图的范围