Nginx 禁止未匹配域名訪問
導語
在最開始配置 nginx 的時候,是修改的default.conf
檔案。檔案中顯示指定了listen 80 default_server;
,也就是沒有匹配到的域名會轉到這裡來處理。接下來修改為只匹配設定的域名,其他返回 404。
解決方案
很簡單的配置就可以。
server { listen80 default_server; server_namelocalhost; #charset koi8-r; #access_log/var/log/nginx/host.access.logmain; location / { return 404; root/usr/share/nginx/html; indexindex.html index.htm; } #error_page404/404.html; # redirect server error pages to the static page /50x.html # error_page500 502 503 504/50x.html; location = /50x.html { root/usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { #proxy_passhttp://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { #roothtml; #fastcgi_pass127.0.0.1:9000; #fastcgi_indexindex.php; #fastcgi_paramSCRIPT_FILENAME/scripts$fastcgi_script_name; #includefastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { #denyall; #} }
多提一句,在nginx.conf
中http
內新增server_tokens off;
可以隱藏版本號。
配置好之後,記得重啟 nginx。
重點在於listen80 default_server;
和return 404
,如此配置,沒有匹配到的域名,包括直接 ip 訪問,都會 404;
以下是我測試配置的流程,各位感興趣可以看下。
修改流程
- 在伺服器供應商中新增一條解析,配置子域名繫結到伺服器中
- 首先是到代理 nginx,訪問成功,是 nginx 預設的頁面。根據上面進行修改後,再次訪問會返回 404
- 為了進一步測試,配置 nginx 代理,將剛才繫結的子域名轉發到 laradock 的 nginx 中。此時訪問會到 laravel 的首頁
-
因為之前配置的原因,首先修改
laradock/nginx/sites/laravel.conf.example
檔案,修改檔名為laravel.conf
,主要是server_name
和root
,內容如下
server { listen 80; listen [::]:80; # For https # listen 443 ssl; # listen [::]:443 ssl ipv6only=on; # ssl_certificate /etc/nginx/ssl/default.crt; # ssl_certificate_key /etc/nginx/ssl/default.key; server_name www.you_site.com; root /var/www/web/public; index index.php index.html index.htm; location / { try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { try_files $uri /index.php =404; fastcgi_pass php-upstream; fastcgi_index index.php; fastcgi_buffers 16 16k; fastcgi_buffer_size 32k; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #fixes timeouts fastcgi_read_timeout 600; include fastcgi_params; } location ~ /\.ht { deny all; } location /.well-known/acme-challenge/ { root /var/www/letsencrypt/; log_not_found off; } error_log /var/log/nginx/laravel_error.log; access_log /var/log/nginx/laravel_access.log; }
-
接下來將
default.conf
修改為解決方案中的配置,然後重啟 - 此時再訪問就是 404