时不时地,我的网站会受到各种 php 文件(我们不托管任何 php 文件)以及各种
wp-content
和 wp-includes
的请求的困扰,我想在 Nginx 配置中拒绝这些请求级别,而不是从我们的网站提供漂亮的 404 页面。
现在我已经在一堆
location
块中添加了两个 server
规则:
server {
server_name www.example.com;
location ~* /wp- {
return 404;
}
location ~ \.php$ {
return 404;
}
location / {
# ...the site's proxy_pass config...
}
listen [::]:443 ssl http2; # managed by Certbot
listen 443 ssl http2; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
server_name www.example.com;
location ~* /wp- {
return 404;
}
location ~ \.php$ {
return 404;
}
location / {
return 301 https://$host$request_uri;
}
listen 80;
listen [::]:80;
}
server {
server_name example.com;
location ~* /wp- {
return 404;
}
location ~ \.php$ {
return 404;
}
return 301 http://www.example.com$request_uri;
listen [::]:443 ssl; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
server_name example.com;
location ~* /wp- {
return 404;
}
location ~ \.php$ {
return 404;
}
if ($host = example.com) {
return 301 https://www.$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
return 404; # managed by Certbot
}
这些不同的
server
块确保 http 请求转到 https,并且对裸域的请求转到 www 子域。现在访问任何类型的 php url 都会导致不同的行为:
如何才能使两个裸域的行为与两个 www 子域相同,例如:匹配这 2 个规则之一的请求会立即导致 404,而不首先触发 301 重定向?
(这些重定向被服务器监控软件捕获,我们不断收到有关重定向百分比高和成功响应百分比低的警告。这真的很烦人。不,我们不想许可这些警告,我们只是希望此类请求不再导致重定向。)
我设法通过将重定向包装到 https www 版本来解决这个问题,如下所示:
location / {
return 301 https://www.example.com$request_uri;
}
我在两个底部
server
块中都做了这个,这似乎工作得很好。