【发布时间】:2021-09-07 16:46:25
【问题描述】:
我是前 Apache 用户,我决定冒险并转向 NGINX。在 Apache 上,我有一些重写规则,如下所述。 我有两个问题:
- 谁能帮我处理这些重写的 NGINX 版本?
- 如何将重写应用到服务器上的所有站点?
提前谢谢你
# 301 Redirect http to https
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 301 Redirect www to https
RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]
# Remove the .html extension
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.html\ HTTP
RewriteRule (.*)\.html$ $1 [R=301]
# Remove index and reference the directory
RewriteRule (.*)/index$ $1/ [R=301]
# Remove trailing slash if not a directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301]
# Forward request to html file, **but don't redirect (bot friendly)**
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.html [L]
更新 在浏览了许多文章之后,我认为我已经提出了以下解决方案 - 请随时发表评论和建议:
server {
# Catch all and redirects to https
listen 80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
server {
# Redirect www to https
server_name www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name www.example.com example.com;
ssl_certificate /etc/ssl/nginx-ssl/bundle.crt;
ssl_certificate_key /etc/ssl/nginx-ssl/example.key;
access_log /var/log/nginx/nginx.vhost.access.log;
error_log /var/log/nginx/nginx.vhost.error.log;
location / {
root /var/www/example.com/html;
index index.html;
# Remove .html extension
if ($request_uri ~ ^/(.*)\.html) {
return 302 /$1;
}
try_files $uri $uri.html $uri/ =404;
}
我没有解决的问题是:
- 如果不是目录,则删除尾部斜杠
- 将请求转发到 html 文件但不重定向(机器人友好)
有人可以帮忙吗?
【问题讨论】:
标签: nginx