nginx - NGINX URLS 重写
问题描述
我是前 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 中的所有重写规则。
将 Apache 重写规则转换为 Nginx - https://www.nginx.com/blog/converting-apache-to-nginx-rewrite-rules/
创建 Nginx 重写规则 - https://www.nginx.com/blog/creating-nginx-rewrite-rules/
如果您在转换过程中遇到任何问题,请在评论中提及。我将在答案中添加。
推荐阅读
- typescript - 在 Typescript / GraphQL 中连接或推断字符串
- angular - 无法在 Angular 测试中模拟子组件
- excel - 有没有办法将右对齐的文本仅移动到excel中的另一个单元格中?
- data-warehouse - 单价和折扣 - 事实或维度表
- java - 如何从 Windows 10 卸载 OpenJDK13(未显示在控制面板中)?
- typescript - 将一个大抽象类拆分为多个+从它继承
- google-cloud-platform - 如何监控 GCP 节点 IP 地址
- css - 如何避免使用Angular CSS minifier合并媒体查询声明变量?
- javascript - ZXing.NET 从 HTML5 视频中解码 PDF417 条码
- windows - 在 Windows 8 上运行 rabbitMQ docker 映像时出现问题,其中包含用于保留容器数据的卷