nginx的重写所有的index.php除白名单有的、重写、名单、nginx

2023-09-02 09:41:08 作者:学校塌了,才是晴天

首先,我试图寻找类似的问题,但解决这些问题均为code专用线,我不能自定义,以适合我的需要。

First of all, I have tried to search for similar questions, but the solutions to those questions were specific lines of code, that I couldn't customise to fit my needs.

我有一个codeigniter安装,我试图从迁移到Apache的nginx的。但是,Apache中的.htaccess是pretty的简单:它会采取白名单,并改写一切以的index.php

I have a Codeigniter installation, and I'm trying to migrate from Apache to nginx. However, in Apache the .htaccess was pretty simple: it would take a whitelist, and rewrite everything else to index.php.

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

然而,在nginx的,我已经试过了,如果和try_files指令,以及与位置插科打诨,都无济于事。我还是新来nginx怎么读取服务器配置和在线教程是有些混乱的贯彻。

However in nginx, I have tried out the if and try_files directives, as well as messing around with locations, to no avail. I'm still new to how nginx reads the server config, and the tutorials online were somewhat confusing to follow through.

此外,在index.php不会在Web根目录,但在子目录服务器

Additionally, the index.php will not be in the web root, but in a subdirectory server.

这一点,因为,我还需要确保即使URI请求与/服务器刚开始不进入目录,但的index.php

Because of this, I also need to make sure even URI requests beginning with /server do not go to the directory, but to index.php

这是我的nginx的虚拟主机配置至今:

This is my nginx virtual host configuration so far:

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 ,但没有一个白名单。我想AP preciate它,如果任何人都可以产生与什么的每一部分做了简短的解释工作的例子。

Which helps to redirect requests to index.php, but doesn't have a whitelist. I would appreciate it if anyone could generate a working example with a brief explanation of what each part does.

推荐答案

我会使用 $ URI 变量如果在位置块来实现这一目标。

I would use the $uri variable and if in a location block to achieve this.

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

另外,作为用于 PATHINFO安全问题中,(讨论)这是一个很好的做法,增加

Also, as for the pathinfo security problems, (discussion) it's a good practice to add

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

位置〜 .PHP $ 块。