Ben Berman
Ben Berman

Reputation: 11

nginx: how to always redirect to different host when we redirect

The title is a bit misleading, but I can't think of a better one.

I'm hosting an nginx server behind CloudFront. The nginx server can be accessed at origin.website.com which is the origin for CloudFront. The CloudFront distribution is hosted at website.com.

Is there a way to make it so that, every time we redirect, we redirect to website.com/$uri rather than origin.website.com/$uri?

I'm trying to cover all my bases, but I do have a specific problem:

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  origin.website.com website.com;
        add_header X-server-choice "default";
        add_header X-heard-uri "$uri";

        root /var/www;
        client_max_body_size 200M;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
                proxy_pass http://localhost:8080;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }
        location /blog {
                alias /var/www/blog;
                index index.php;
                try_files $uri $uri/ @site_rewrite;
        }

        location @site_rewrite {
                rewrite ^/blog/(.*)$ /blog/index.php?$1;
        }

        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  /var/www/$fastcgi_script_name;
                include        fastcgi_params;
        }

        location ~ /\.ht {
                deny  all;
        }

}

Whenever I go to website.com/blog it redirects to origin.website.com/blog/. It seems to be going through location /blog and redirecting in the try_files $uri $uri/ @site_rewrite without going through the site_rewrite.

Any ideas? Thanks!

Upvotes: 1

Views: 192

Answers (1)

Faisal Memon
Faisal Memon

Reputation: 1107

I think you could put a full url for the rewrite target, ie

rewrite ^/blog/(.*)$ $scheme://website.com/blog/index.php?$1 redirect;

Upvotes: 1

Related Questions