nginx 将 url 重定向到一个完全不同的模式

nginx redirect a url into a complete different pattern

在我的 nginx 中,我想将 /media/api/static/terms.html 重定向到 /terms-of-use 并且我的 nginx 具有以下配置:

 listen 80;

    server_name _;

    root /var/www/html/website;

    index index.php index.html;

    charset utf-8;

    keepalive_timeout 65;
    server_tokens off;
    sendfile off;

    proxy_buffer_size   128k;
    proxy_buffers   4 256k;
    proxy_busy_buffers_size   256k;

    location /manifest.json {
        default_type application/x-web-app-manifest+json;
    }

    location /.well-known/apple-app-site-association {
        default_type application/json;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include   fastcgi_params;

        fastcgi_param PATH_INFO  $fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;

        fastcgi_pass website:9000;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_read_timeout 300s;

    }

    location /robots/robots-gr.txt {
       default_type text/plain;
    }

    location /robots/robots-cy.txt {
       default_type text/plain;
    }

    rewrite ^/robots.txt$ /robots/robots-gr.txt last;

    location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|html|xml|otf|ttf|eot|woff|svg|pdf)$ {
        access_log off;
        expires 30d;
        tcp_nodelay off;

        ## Set the OS file cache.
        open_file_cache max=3000 inactive=120s;
        open_file_cache_valid 45s;
        open_file_cache_min_uses 2;
        open_file_cache_errors off;
    }

    location ~ /\.ht {
        deny all;
    }
  }
}

我尝试了以下操作:

    location /media/api/static/terms.html {
      return 301 /terms-of-use
    }

但是 url 没有 301 重定向。我还尝试了以下方法:

    location /media/api/static/terms.html {
        rewrite  $scheme://$host/terms-of-use last;
    }

但是我还是没有301重定向。你有什么想法吗?

正则表达式匹配位置比前缀位置具有更高的优先级。这就是为什么你的

location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|html|xml|otf|ttf|eot|woff|svg|pdf)$ {
    ...
}

优先于

location /media/api/static/terms.html {
    return 301 /terms-of-use
}

official documentation 中描述的为请求处理选择位置的完整算法。

您可以通过多种方式解决此问题:

  • 使用精确位置匹配:

    location = /media/api/static/terms.html {
        return 301 /terms-of-use;
    }
    
  • 使用 ^~ 位置修饰符:

    location ^~ /media/api/static/terms.html {
        return 301 /terms-of-use;
    }
    
  • server 上下文中使用重写规则:

    rewrite ^/media/api/static/terms\.html$ /terms-of-use permanent;