Laravel 官方文檔推薦的 Nginx 配置

參考資料

https://learnku.com/articles/25861
https://imququ.com/post/web-security-and-response-header.html
感謝兩位作者的付出!

server {
    # 監(jiān)聽 HTTP 協(xié)議默認(rèn)的 [80] 端口。
    listen 80;
    # 綁定主機(jī)名 [example.com]。
    server_name example.com;
    # 服務(wù)器站點根目錄 [/example.com/public]。
    root /example.com/public;

    # 添加幾條有關(guān)安全的響應(yīng)頭;與 Google+ 的配置類似,詳情參見上述鏈接。
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    # 站點默認(rèn)頁面;可指定多個,將順序查找。
    # 例如,訪問 http://example.com/ Nginx 將首先嘗試「站點根目錄/index.html」是否存在,不存在則繼續(xù)嘗試「站點根目錄/index.htm」,以此類推...
    index index.html index.htm index.php;

    # 指定字符集為 UTF-8
    charset utf-8;

    # Laravel 默認(rèn)重寫規(guī)則;刪除將導(dǎo)致 Laravel 路由失效且 Nginx 響應(yīng) 404。
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # 關(guān)閉 [/favicon.ico] 和 [/robots.txt] 的訪問日志。
    # 并且即使它們不存在,也不寫入錯誤日志。
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    # 將 [404] 錯誤交給 [/index.php] 處理,表示由 Laravel 渲染美觀的錯誤頁面。
    error_page 404 /index.php;

    # URI 符合正則表達(dá)式 [\.php$] 的請求將進(jìn)入此段配置
    location ~ \.php$ {
        # 配置 FastCGI 服務(wù)地址,可以為 IP:端口,也可以為 Unix socket。
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        # 配置 FastCGI 的主頁為 index.php。
        fastcgi_index index.php;
        # 配置 FastCGI 參數(shù) SCRIPT_FILENAME 為 $realpath_root$fastcgi_script_name。
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        # 引用更多默認(rèn)的 FastCGI 參數(shù)。
        include fastcgi_params;
    }
    # 通俗地說,以上配置將所有 URI 以 .php 結(jié)尾的請求,全部交給 PHP-FPM 處理。

    # 除符合正則表達(dá)式 [/\.(?!well-known).*] 之外的 URI,全部拒絕訪問
    # 也就是說,拒絕公開以 [.] 開頭的目錄,[.well-known] 除外
    location ~ /\.(?!well-known).* {
        deny all;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容