【问题标题】:In NGINX 'location ~ .*' does not match any string在 NGINX 'location ~ .*' 中不匹配任何字符串
【发布时间】:2021-11-10 09:47:33
【问题描述】:

在以下站点配置文件中,我正在尝试:

  1. 在第一次访问时加载 index.php。

  2. 加载出现在 /uploads/ 目录中的文件。

  3. 任何其他请求仍应由 index.php 处理。

    server {
     listen 80 default_server;
     listen [::]:80 default_server;
    
     root /home/va/www/example;
    
     # Add index.php to the list if you are using PHP
     # index index.php;
    
     server_name example.dev;
    
     location ~ .*
     {
         try_files /dev/null @php;
     }
    
     location /uploads/
     {
         try_files $uri =404;
         expires 30d;
     }
    
     location @php
     {
         include snippets/fastcgi-php.conf;
    
         #pretty url
         fastcgi_param SCRIPT_FILENAME $document_root/index.php;
    
         fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
     }
    }
    

但是,最后一部分中断了。换句话说:

/                  works
/?test=test        works
/uploads/test.jpeg works
/random_string     does not work and returns 404 error

我的理解是location ~ .*别无选择,只能匹配一切。 404错误来自哪里?

【问题讨论】:

    标签: nginx-location


    【解决方案1】:

    好的。在进行了更多工作并完全重写了逻辑之后,我从The MediaWiki Nginx guide 得到了灵感。最终的解决方案是:

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        
        root /home/va/www/example;
        
        server_name example.dev;
        
        location = /
        {
            return 301 /home;
        }
        location = /index.php
        {
            include snippets/fastcgi-php.conf;
            
            #pretty url
            fastcgi_param SCRIPT_FILENAME $document_root/index.php;
            
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        }
        location /uploads/
        {
            try_files $uri =404;
            expires 30d;
        }
        location /
        {
            rewrite ^/(?<pagename>.*)$ /index.php;
        }
        
        location /classes/ { deny all; }
        location /config/ { deny all; }
    }
    

    然后我将在 PHP 中使用$_SERVER['REQUEST_URI'] 来路由请求。希望这个解决方案能对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 2012-01-16
      相关资源
      最近更新 更多