Nginx的location
指令不能直接匹配查詢參數,所以需要通過其他方式來處理。這里是一個使用if
指令結合查詢參數來實現的方法。該方法會在請求路徑中帶有特定查詢參數時返回404。
使用if
指令匹配查詢參數
-
打開Nginx配置文件:
sudo vim /etc/nginx/sites-available/default
-
添加以下配置:
在
server
塊中添加一個location
塊和if
語句來匹配特定的查詢參數并返回404狀態碼。server {listen 80;server_name harbor.shgbitai.com;location / {# 其他正常的配置}# 匹配路徑為/account/sign-in,帶有globalSearch查詢參數的請求,并返回404location /account/sign-in {if ($arg_globalSearch) {return 404;}# 正常的處理邏輯try_files $uri $uri/ =404;}error_page 404 /404.html;location = /404.html {internal;root /usr/share/nginx/html; # 這里需要指向您的404錯誤頁面} }
-
創建或修改404錯誤頁面:
確保你有一個404錯誤頁面,例如
/usr/share/nginx/html/404.html
。可以使用以下命令創建一個簡單的404頁面:echo "404 Not Found - The requested resource could not be found." | sudo tee /usr/share/nginx/html/404.html
-
測試Nginx配置:
在重新加載Nginx之前,先測試配置文件是否有語法錯誤:
sudo nginx -t
如果測試通過,你應該會看到類似如下的輸出:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
-
重新加載Nginx:
重新加載Nginx以使更改生效:
sudo systemctl reload nginx
解釋
if ($arg_globalSearch)
:在location /account/sign-in
塊中,使用if
語句檢查globalSearch
查詢參數是否存在。如果存在,則返回404狀態碼。location = /404.html { internal; root /usr/share/nginx/html; }
:配置404錯誤頁面的位置和內容。
通過這種方法,當用戶訪問https://XXXXX/account/sign-in?globalSearch=任意值
時,會直接返回404頁面。確保根據實際的Nginx配置文件路徑和服務器環境調整相應的路徑和配置。