首页 文章

使用重写和有效的mime类型配置NGINX的正确方法

提问于
浏览
0

我正在尝试测试NGINX并可能从Apache切换 . 我读过nginx的速度要快得多,但我希望能够做到这一点 . 我在使用NGINX的配置以匹配我的Apache设置时遇到问题 - 主要是重写规则 . 我将解释我的应用程序如何工作以及我希望能在NGINX中做些什么 .

目前我的应用程序处理发送到服务器的所有REQUEST_URI . 即使URI不存在,我的应用程序也会处理该URI的处理 . 我能够这样做是因为Apache的重写规则 .

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?_url=$1 [QSA,NC]
</IfModule>

正如你可以看到文件或目录是否甚至没有检查查询字符串,我只是通过PHP变量$ _SERVER ['REQUEST_URI']来处理URI本身,该变量在NGINX中设置为 fastcgi_param REQUEST_URI $request_uri ;.我想用NGINX完成这个确切的事情,但我只是那种成功 .

所以基本上,如果domain.com/register.php存在,那么它将转到该URL,如果不是,它将被重定向到domain.com/index.php并且应用程序从那里处理URI .

这是我服务器的配置文件 . 这包含在nginx.conf文件的底部

server {
    listen ####:80;
    server_name ####;

    charset utf-8;

    access_log /var/www/#####/logs/access-nginx.log;
    error_log /var/www/#####/logs/error-nginx.log;

    root /var/www/######/public/;

    location / {
        index index.php index.html;
        include /etc/nginx/mime.types;
        try_files $uri /index.php?_url=$1;

        include /etc/nginx/fastcgi.conf;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index  index.php;
        fastcgi_pass unix:/var/run/php-fpm.socket;

        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        rewrite_log on;
    }
}

所以这种作品 . 我的意思是try_files $ uri /index.php?_url=$1指令正在按照我想要的方式处理URI,但MIME类型似乎不起作用 . 一切都被处理为text / html . 这意味着我的.css和.js文件必须转换为.php文件和附加的标头才能正确处理 . 图像和字体文件似乎正常运行,但Chrome仍然将mime类型显示为html . 我有mime.types文件,所以我无法弄清楚它为什么这样做 . 我确实尝试使用“重写”指令来处理try_files正在做的事情,但这不起作用 .

这是我在位置/块中尝试的重写:

if (!-e $request_filename){
    rewrite ^(.*)$ /index.php?_url=$1;
}

所以我的问题是:如何在为文件自动提供适当的mime类型的同时正确地重写我的uri中不存在的文件和目录?

1 回答

  • 0

    我最终解决了自己的问题 . 我在这里要做的就是自己处理PHP文件,并且需要一段时间才能确定 . 这是最终的.conf文件,它发送正确的mime类型,并重写我需要它的方式 . 希望这对其他人也有帮助 .

    server {
        listen #######:80;
        server_name ######;
    
        charset utf-8;
    
        access_log /var/www/######/logs/access-nginx.log;
        error_log /var/www/#######/logs/error-nginx.log;
    
        root /var/www/#########/public/;
    
        location ~ \.php$ {
            include /etc/nginx/mime.types;
            try_files $uri /index.php?_url=$1;
            include /etc/nginx/fastcgi.conf;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_index  index.php;
            fastcgi_pass unix:/var/run/php-fpm.socket;
    
        }
    
        location / {
            index index.php index.html;
            include /etc/nginx/mime.types;
            try_files $uri /index.php?_url=$1;
    
            autoindex on;
            autoindex_exact_size off;
            autoindex_localtime on;
            rewrite_log on;
        }
    }
    

    使用 location ~ .php$ 部分使得只有PHP文件被发送到php-fpm . 我还使用 try_files 指令来处理将所有URI 's that don' t存在到我的脚本中,这是我的应用程序所期望的 . 希望这有助于其他人!

相关问题