Nginx禁用目录浏览

分享于 

4分钟阅读

互联网

  繁體

问题:

我有一个Django应用程序,web服务器是Nginx。

应用程序位于/home/rouizi/blog,假设域名是example.com

以下是我的Nginx配置:

/etc/nginx/nginx.conf


user www-data;


worker_processes auto;



pid /run/nginx.pid;


include /etc/nginx/modules-enabled/*.conf;



events {


 worker_connections 1024;


}



http {


 sendfile on;


 tcp_nopush on;


 tcp_nodelay on;


 types_hash_max_size 2048;



 include /etc/nginx/mime.types;


 default_type application/octet-stream;



 ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE


 ssl_prefer_server_ciphers on;



 access_log /var/log/nginx/access.log;


 error_log /var/log/nginx/error.log;



 include /etc/nginx/conf.d/*.conf;



 add_header X-Content-Type-Options nosniff;


 add_header X-Frame-Options SAMEORIGIN;


 add_header X-XSS-Protection "1; mode=block";



 server_tokens off;


 keepalive_timeout 75;


}



/etc/nginx/conf.d/example.conf


server {


 if ($host = www.example.com) {


 return 301 https://$host$request_uri;


 } # managed by Certbot



 if ($host = example.com) {


 return 301 https://$host$request_uri;


 } # managed by Certbot



 listen 80;


 server_name example.com www.example.com;


 return 301 https://example.com$request_uri;


}



server {


 listen 443 ssl http2 default_server;


 listen [::]:443 ssl http2 default_server;



 # ssl stuff



 server_name example.com www.example.com;


 root /home/rouizi/blog/;


 index index.html;



 location /static {


 alias /home/rouizi/blog/staticfiles/;


 }



 location / {


 proxy_set_header Host $http_host;


 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;


 proxy_redirect off;


 if (!-f $request_filename) {


 proxy_pass http://127.0.0.1:8000;


 break;


 }


 }



 gzip on;


 gzip_comp_level 3;


 gzip_types text/plain text/css application/javascript image/*;


}



我发现,如果在server_name指令中放置ip地址而不是域名,目录浏览被禁用:

/etc/nginx/conf.d/example.conf


# ...



server {


 # ...


 # ssl stuff



 server_name 139.151.187.143;



 # ...



}




答案1:

典型设置的工作方式如下:

  • /static中的所有内容都由web服务器处理(这是location /static {}块关于的内容:alias指向Django collectstatic命令放置静态文件的目录)
  • 如有必要,类似处理/media位置
  • 其他所有内容都转发到wsgi应用程序(这意味着nginx服务器不会直接访问您的程序文件)

if (!-f $request_filename) { 阻止)将请求转发到您的wsgi应用程序。


答案2:

你需要配置在127.0.0.1:8000上运行的应用程序来阻止这些请求。