regex - nginx将所有白名单重写为index.php

标签 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不在Web根目录中,而是在子目录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,但没有白名单。如果有人可以生成一个工作示例并简要说明每个部分的功能,我将不胜感激。

最佳答案

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

关于regex - nginx将所有白名单重写为index.php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11623267/

相关文章:

php - 错误 undefined variable : result + Error Invalid argument supplied for foreach() in CodeIgniter 2

php - 如何从表中获取随机行值并将其存储在数组中以单独调用

regex - LibXML中的xPath可以是正则表达式类型吗

c# - 格式化长日期时间字符串以删除 T 字符

javascript - JavaScript/ECMAScript 是常规语言吗?

javascript - 我自己对 codeigniter 中的默认 .htaccess 文件进行了一些更改,现在我的注销链接不起作用

javascript - 仅对某些 css 和 javascript 文件利用浏览器缓存

.htaccess - 测试 gzip 是否在本地工作

regex - 如何在 Perl 中使用 REGEX 查找字符串中的第 n 个字符或数字

codeigniter - ckeditor 显示 <p>Text</p> 而不是显示 HTML