如何配置nginx将上传目录的请求重定向到生产服务器?

时间:2015-12-05 作者:Colin

我只是被nginx弄湿了脚。过去我用过。htaccess文件位于/wp content/uploads中,因此如果我的开发人员或临时服务器没有该文件,它会重定向到生产服务器:

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteBase /wp-content/uploads/
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*) http://production.server.com/m/wp-content/uploads/$1 [L,P]

</IfModule>
我在nginx做这件事运气不好。部分原因可能是因为我的站点此时位于子目录(/m/)中。

# Tells nginx which directory the files for this domain are located
root         /srv/www/example/htdocs;
index               index.php;

    # Subdirectory location settings

    location /m {
            index index.php;
            try_files $uri $uri/ /m/index.php?$args;
            location /m/wp-content/uploads {
                    try_files $uri $uri/ @prod_svr;
            }
    }
    location @prod_svr {
            proxy_pass http://production.server.com/m/wp-content/uploads$uri;
    }
任何想法都会受到极大的赞赏。

2 个回复
SO网友:Ben Cole

您可以尝试以下方式:

server {
    root /srv/www/example/htdocs;
    index index.php;

    # Matches any URL containing /wp-content/uploads/    
    location ~ "^(.*)/wp-content/uploads/(.*)$" {
        try_files $uri @prod_serv;
    }

    # Will redirect requests to your production server
    location @prod_serv {
        rewrite "^(.*)/wp-content/uploads/(.*)$" "http://yourdomain.com/m/wp-content/uploads/$2" redirect;
    }

    # The rest of your location blocks...
    location /m {
        index index.php;
        try_files $uri $uri/ /m/index.php?$args;
    }
}

SO网友:Kevin Leary

如果对任何人有用,我在WordPress本地主机环境中使用了类似的设置来处理此问题,但有一些有用的区别:

我喜欢使用一个变量来设置我的生产环境,它允许我在多个服务器块中快速重用这个变量

  • 我在重写时中断,而不是重定向,这有助于避免与可能匹配相同URL的其他请求出现问题,这里有一个基本示例:

    server {
        server_name mywebsite.dev;
        set $production mywebsite.wpengine.com;
    
        # Redirect requests to /wp-content/uploads/* to production server
        location @prod_uploads {
            rewrite "^(.*)/wp-content/uploads/(.*)$" "https://$production/wp-content/uploads/$2" break;
        }
    
        # Rule for handling requests to https://mywebsite.dev/wp-content/uploads/
        location ~ "^/wp-content/uploads/(.*)$" {
            try_files $uri @prod_uploads;
        }
    }
    
    实际上,我包括location ~ "^/wp-content/uploads/(.*)$" 名为wp-common.conf. 这允许我在许多不同的环境中使用相同的WordPress nginx配置规则运行$production开关。

  • 相关推荐

    WP_REDIRECT导致无限循环

    Goal: 我修改了permalink,以显示特定类别的类别名称:grill rezepte。默认情况下,永久链接为:https://website.com/post-title 现在只有烧烤餐厅:https://website.com/grill-rezepte/post-title因此,我想在所有grill Recipes上设置301重定向,以便它们移动到新的URL。我有下面的代码(见下文),它会导致一个无限循环。Code:add_action(\'template_redirect\', \'pos