【问题标题】:nginx rewrite all to index.php except whitelistnginx 将除白名单外的所有内容都重写为 index.php
【发布时间】:2012-07-22 07:44:30
【问题描述】:

首先,我尝试搜索类似的问题,但这些问题的解决方案是特定的代码行,我无法根据自己的需要进行自定义。

我安装了 Codeigniter,我正在尝试从 Apache 迁移到 nginx。然而,在 Apache 中,.htaccess 非常简单:它需要一个白名单,并将其他所有内容重写为 index.php

RewriteEngine on
RewriteCond $1 !^(index\.php|css|images|core|uploads|js|robots\.txt|favicon\.ico)
RewriteRule ^(.*)$ /index.php/$1 [L]

但是,在 nginx 中,我尝试了 if 和 try_files 指令,以及弄乱位置,但无济于事。我对 nginx 如何读取服务器配置仍然很陌生,并且在线教程有些令人困惑。

另外,index.php 将不在网络根目录中,而是在子目录server

因此,我还需要确保即使以 /server 开头的 URI 请求也不会转到目录,而是转到 index.php

这是我目前的 nginx 虚拟主机配置:

server {
    listen 80;
    server_name example.com;

    root /home/example/public_html;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;


    location / {
        index index.htm index.html index.php;
    }

    location ~ \.php$ {
        fastcgi_pass        unix:/var/run/php-fpm/example.sock;
        include             fastcgi_params;
        fastcgi_param       PATH_INFO $fastcgi_script_name;
        fastcgi_param       SCRIPT_FILENAME $document_root$fastcgi_script_name;

    }

    location ~* ^.*(/|\..*) { 
        try_files $uri $uri/ /server/index.php;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

这有助于将请求重定向到index.php,但没有白名单。如果有人能生成一个工作示例并简要说明每个部分的作用,我将不胜感激。

【问题讨论】:

    标签: regex .htaccess codeigniter nginx rewrite


    【解决方案1】:

    我会在location 块中使用$uri 变量和if 来实现这一点。

    location / {
        if ( $uri !~ ^/(index\.php|css|images|core|uploads|js|robots\.txt|favicon\.ico) ) {
            rewrite ^ /server/index.php last;
        }
    }
    

    另外,对于pathinfo security problems,(discussion),添加

    try_files $uri =403;
    fastcgi_split_path_info ^(.+.php)(.*)$;
    

    location ~ \.php$ 块。

    【讨论】:

    • 谢谢,成功了!我也要研究一下 pathinfo 的东西,看起来很有趣。
    • 根据 IfIsEvild 文档,重写 ... 最后;是安全的,但欢迎提出建议(当然,这是某种 wiki)。
    • 就像一个魅力。虽然可能会很好地了解是否可以将系统目录的内容添加到该白名单中。
    猜你喜欢
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2022-08-19
    • 2010-10-07
    相关资源
    最近更新 更多