skip to Main Content

I’ve been converting over my Apache configs to Nginx and got stuck on one of the redirects.

I’m trying to redirect DomainA.co.nz to https://www.DomainB.co.nz/specific-page.

Everything i try it redirects but just to https://www.DomainB.co.nz

This is the Apache config that works fine

<VirtualHost *:80>
 ServerName DomainA.co.nz
 ServerAlias www.DomainA.co.nz
 Redirect permanent / https://www.DomainB.co.nz/specific-page/
</VirtualHost>

And this is the nginx config:

server {
    listen 80;
    server_name DomainA.co.nz www.DomainA.co.nz ;
    
    location ~ / {
        rewrite ^(.*)$ https://www.DomainB.co.nz/specific-page redirect;
        #return 301 https://www.DomainB.co.nz/specific-page;
    }
}

I’ve tried both using rewrite and return which is why return is there commented out at present. neither seem to make a difference. I’ve also try redirecting to http instead and that does the same thing.

I’ve also tried with and without the location block. Seems to act the same. Looking at various results online i’ve tried location / location ~ / location = /

To test I’ve been using incognito/private browsing and different browsers, completely clearing entire cache just to be sure. Even tried on different computers.

2

Answers


  1. Try adding the ^ char to indicate the start of the RegEx pattern (root URI):

    location ~ ^/
    

    That ensures that all URIs start with "/" (e.g. /, /foo, /bar/baz, etc)

    Login or Signup to reply.
  2. Try this:

    rewrite ^(.*)$ /somePage;
    

    Test config

    redir.local and http://www.redir.local domains added to local /etc/hosts file

    server {
        listen 192.168.0.1:80;
        server_name redirect.local www.redirect.local;
        rewrite ^(.*)$ /somePage;
        location =/somePage {
            return 200 "Request uri: $uri n/somePage location example output.n";
            add_header Content-Type text/plain;
        }
    
    }
    
    $ nginx -s reload
    

    Check with curl

    $ curl www.redir.local
    

    Output:

    Request uri: /somePage
    /somePage location example output.
    

    UPD1

    Or if you need 301 redirect, try something like:

    ...
    location / {
      return 301 http://www.redir.local/somePage;
    }
    location =/somePage {
      return 200 "Request uri: $uri n/somePage location example output.n";
      add_header Content-Type text/plain;
    }
    ...
    

    in browser you will redirected to /somePage
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search