首页 > 解决方案 > NGINX URLS 重写

问题描述

我是前 Apache 用户,我决定冒险并转向 NGINX。在 Apache 上,我有一些重写规则,如下所述。我有两个问题:

  1. 有人可以帮我处理这些重写的 NGINX 版本吗?
  2. 如何将重写应用到服务器上的所有站点?

先感谢您

# 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;
      }

我还没有解决的问题是:

  1. 如果不是目录,则删除尾部斜杠
  2. 将请求转发到 html 文件但不重定向(机器人友好)

有人可以帮忙吗?

标签: nginx

解决方案


这是一项非常简单的任务,所以不要害怕。我正在与您分享两个文档,您可以从中轻松了解 Nginx 中的所有重写规则。

将 Apache 重写规则转换为 Nginx - https://www.nginx.com/blog/converting-apache-to-nginx-rewrite-rules/

创建 Nginx 重写规则 - https://www.nginx.com/blog/creating-nginx-rewrite-rules/

如果您在转换过程中遇到任何问题,请在评论中提及。我将在答案中添加。


推荐阅读