nginx将所有内容重写为index.php,白名单除外

时间:2012-07-24 02:27:21

标签: regex .htaccess codeigniter nginx rewrite

首先,我试图搜索类似的问题,但这些问题的解决方案是特定的代码行,我无法自定义以满足我的需求。

我有一个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,但没有白名单。如果有人能够生成一个工作示例并简要解释每个部分的作用,我将不胜感激。

1 个答案:

答案 0 :(得分:13)

我会在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$区块。

相关问题