rovac
rovac

Reputation: 2073

nginx redirect with a subdomain and naked domain

I am attempting to figure out a redirect for my domain in my nginx config. I have these three domain names:

domain.com //points to server 1
www.domain.com //points to hubspot server 2, no a record to change naked domain
app.domain.com //points to server 1

Everything that I am trying is redirecting ALL urls to www.domain.com!

What am I doing wrong?

One attempt, redirects everything:

server {
    listen 80;
    server_name domain.com;
    return 301 www.domain.com;
}

server {
    root var/www/domain/public;
    index index.php index.html;
    server_name app.domain.com;
}

another attempt, redirects everything:

server {
    listen 80;
    root var/www/domain/public;
    index index.php index.html;
    server_name domain.com app.domain.com;
    return 301 www.domain.com
}

This one just totally breaks my config:

server {
    listen 80;
    root var/www/domain/public;
    index index.php index.html;
    server_name domain.com app.domain.com;
  
    location domain.com {
      return 301 www.domain.com;
    }
}

Update:

I've updated my config to say this:

server {
        server_name     domain.com;
        return          301 $scheme://www.domain.com$request_uri;

}

server {
    root /var/www/domain/public;
    index index.php index.html;
    server_name app.domain.com;


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

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }
}

Here is what currently is happening:

What currently happens with the above is:

Some friends of mine testing the address for me say they are being correctly 301 redirected, but a few are not (including myself)

Here is the printout from the curl command:

HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.3 (Ubuntu)
Date: Sun, 09 Aug 2020 22:33:49 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: ht tp://www.domain.com/

HTTP/1.1 200 OK
Date: Sun, 09 Aug 2020 22:33:49 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 54566
Connection: keep-alive

Upvotes: 1

Views: 3325

Answers (1)

qwsj
qwsj

Reputation: 456

www.example.com and app.example.com use the same root directory? If yes, see example below.

For example.com if you need redirect to www subdomain:

server {
    listen 80;
    server_name example.com;
    return 301 http://www.example.com$request_uri;
}

For www.example.com and app.example.com without redirect and output data from /var/www/example/public:

server {
    listen 80;
    server_name www.example.com app.example.com;

    root /var/www/example/public;
    index index.php index.html;
}

Upvotes: 1

Related Questions