Nginx 禁止未匹配域名訪問

導語

在最開始配置 nginx 的時候,是修改的 default.conf 文件。文件中顯示指定了 listen 80 default_server;,也就是沒有匹配到的域名會轉到這裏來處理。接下來修改爲只匹配設置的域名,其他返回 404。

解決方案

很簡單的配置就可以。

server {
    listen       80 default_server;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        return 404;
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 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_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

多提一句,在 nginx.confhttp 內添加 server_tokens off; 可以隱藏版本號。
配置好之後,記得重啓 nginx。
重點在於 listen 80 default_server;return 404,如此配置,沒有匹配到的域名,包括直接 ip 訪問,都會 404;
以下是我測試配置的流程,各位感興趣可以看下。

修改流程

  1. 在服務器供應商中添加一條解析,配置子域名綁定到服務器中
  2. 首先是到代理 nginx,訪問成功,是 nginx 默認的頁面。根據上面進行修改後,再次訪問會返回 404
  3. 爲了進一步測試,配置 nginx 代理,將剛纔綁定的子域名轉發到 laradock 的 nginx 中。此時訪問會到 laravel 的首頁
  4. 因爲之前配置的原因,首先修改 laradock/nginx/sites/laravel.conf.example 文件,修改文件名爲 laravel.conf,主要是 server_nameroot,內容如下
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;
}
  1. 接下來將 default.conf 修改爲解決方案中的配置,然後重啓
  2. 此時再訪問就是 404

參考資料:Nginx 的 default_server 指令nginx 修改並隱藏版本號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章