Nginx 在新安裝時返回 404

Nginx 在新安裝時返回 404

在 Linux Mint 20.3 上,我為本地網站開發進行了工作設定:

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

    server_name cbp.local;

    root /home/gacek/html/cbp/public;

    index           index.php;

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

    if (!-d $request_filename) {
            rewrite     ^/(.+)/$ /$1 permanent;
    }

    location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        }
}

這是一個位於/home/gacek/html/cbp目錄中的 Laravel 應用程序,index.php入口點位於/public子資料夾中。

全新安裝 Linux Mint 21.1 後,相同的 nginx 設定給了我 404 not found:

404 未找到 nginx/1.18.0 (Ubuntu)

我試過:

  • 調整目錄的所有權: sudo chown -R gacek:www-data /home/gacek/html/cbp

  • 擴大權限:sudo chmod -R 776 /home/gacek/html/cbp

  • 建立符號連結並調整 nginx 設定文件sudo ln -s /home/gacek/html/cbp /var/www/

我嘗試的最後一個是因為以下配置工作得很好:

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

    server_name example.local;

    root /var/www/test;
    index index.php;

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

    location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }
}

為什麼這個 nginx 站台設定不起作用?兩者的差別在哪裡呢?

編輯

我已經使用更改了配置Laravel 文檔中的指南

server {
    listen 80;
    listen [::]:80;
    server_name cbp.local;
    root /home/gacek/html/cbp/public;
 
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
 
    index index.php;
 
    charset utf-8;
 
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
 
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }
 
    error_page 404 /index.php;
 
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME /home/gacek/html/cbp/public$fastcgi_script_name;
    }
 
    location ~ /\.(?!well-known).* {
        deny all;
    }
}

更改後,頁面上顯示的錯誤更改為:

File not found.

現在我在 nginx 的錯誤日誌中收到以下錯誤:

在此輸入影像描述

答案1

在我看來,您已經完成了大部分工作- 您已經設置了一個特定的目錄來託管內容並向該目錄應用了適當的權限,儘管您還沒有確認nginx 正在以什麼用戶身份運行,以及該用戶是否是是www-data主機上群組。

我建議將 nginx 正在運行的用戶添加到www-data群組中,並確保該群組具有適當的權限

我實際上建議您不要像您所做的那樣默認使內容目錄可寫,除非您有特定的原因這樣做 - 如果您確實有特定的原因這樣做,我可能會創建一個專用的子目錄這是可寫的,而根不可寫。

綜上所述,大概是:

usermod -aG nginx www-data
chmod -R 755 /home/gacek/html/cbp

實際上,您可以進一步強化目錄權限,僅將上述內容套用至目錄/子目錄,並套用至chmod 644所有檔案。

編輯:已代表您在線搜索別處,這似乎是潛在問題的一個很好的候選者:您可能ProtectHome=true在 systemd 初始化文件中有php-fpm.service.

  1. 設定ProtectHome=false/etc/systemd/system/multi-user.target.wants/php-fpm.service
  2. systemctl daemon-reload
  3. systemctl restart nginx.service
  4. systemctl restart php-fpm.service

諷刺的是,我個人確實注意到,您最初將程式碼放在主資料夾中而不是例如,/var/www/html/但決定將其保留給我自己,這很奇怪 - 事實證明它是相關的!

相關內容