Nginx配置不起作用

时间:2016-11-30 23:30:35

标签: nginx

我刚刚从Apache切换到nginx,它仍然需要一些习惯(以及大量的学习)。

我正在运行具有此配置的Pagekit网站:https://gist.github.com/DarrylDias/be8955970f4b37fdd682

server {
    listen 80;
    listen [::]:80;

    # SSL configuration

    listen 443 ssl;
    listen [::]:443 ssl;

    ssl                 on;
    ssl_certificate     /etc/ssl/private/mydomain.com.crt;
    ssl_certificate_key /etc/ssl/private/mydomain.com.private.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;

    ssl_client_certificate  /etc/ssl/private/cloudflare.origin-pull-ca.pem;
    ssl_verify_client       on;

    server_name mydomain.com www.mydomain.com;

    root /home/vhosts/domains/mydomain.com/public/;

    index index.php;

    # Leverage browser caching of media files for 30 days
    location ~* \.(?:ico|css|js|gif|jpe?g|png|ttf|woff)\$ {
        access_log off;
        expires 30d;
        add_header Pragma public;
        add_header Cache-Control "public, mustrevalidate, proxy-revalidate";
    }

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # Deny access to sensitive folders
    location ~* /(app|packages|storage|tmp)/.*$ { 
        return 403; 
    }

    # Deny access to files with the following extensions
    location ~* \.(db|json|lock|dist|md)$ { 
        return 403;
    }

    # Deny access to following files 
    location ~ /(config.php|pagekit|composer.lock|composer.json|LICENSE|\.htaccess) { 
        return 403; 
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php7-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_param  HTTP_MOD_REWRITE  On;
    }
}

不幸的是,许多人(包括我)都存在这样的问题:带有js|css|jpg|<etc>扩展名的文件会收到403响应,因为它们位于app or packages目录中。

我尝试过多个正则表达式尝试在nginx中为这些文件赋予location更高的优先级,但它们似乎没有效果。

如何更改此配置文件以允许这些类型的文件,但仍然会在这些目录中的所有其他文件上返回403?

编辑:文件网址看起来像https://example.com/app/js/something.min.js?v=1921,或许因为?v=1921而无效?

1 个答案:

答案 0 :(得分:2)

根据nginx's document

  

nginx按照配置文件

中列出的顺序检查正则表达式给出的位置

首先,您需要将上一个location移到顶部。

然后尝试匹配静态文件的正则表达式也不正确。美元符号“$”应该与路径末尾匹配,但它被前一个反斜杠“\”转义(因此它实际匹配字符“$”)。删除反斜杠将解决您的问题:

location ~* \.(?:ico|css|js|gif|jpe?g|png|ttf|woff)$ {
    ...
}