Moses
Moses

Reputation: 700

Configure nginx vhosts by path

I want to serve my projects by first item in the path, for example http://example.com/projectname should serve a project in /usr/share/nginx/html/projectname.

This is what my configurations look like:

server {
    listen 80;
    server_name example.com www.example.com;
    rewrite ^/(.*) https://example.com/$1 permanent;
}

server {
    listen       443 ssl;
    listen       [::]:443 ssl;

    ssl_certificate "/etc/ssl/XX.pem";
    ssl_certificate_key "/etc/ssl/XX.key";
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
    server_name  example.com/$1 www.example.com/$1;

    access_log /var/log/nginx/nginx.vhost.access.log;
    error_log /var/log/nginx/nginx.vhost.error.log;

    location /projectname {
        root   /usr/share/nginx/html/projectname ;
        index  index.html;

        try_files $uri $uri/ /index.html?$args;
    }
}

Observation: When i visit the configured domain it routes to nginx defualt page instead of displaying the expected project.

Upvotes: 2

Views: 2382

Answers (2)

NetanMangal
NetanMangal

Reputation: 354

3 Changes:

  1. Instead of rewrite, do return 301
  2. In second server block, don't have /$1 at the end of server_names
  3. remove index index.html from location /projectname block
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://example.com/$request_uri;
}

server {
    listen       443 ssl;
    listen       [::]:443 ssl;

    ssl_certificate "/etc/ssl/XX.pem";
    ssl_certificate_key "/etc/ssl/XX.key";
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
    server_name  example.com www.example.com;

    access_log /var/log/nginx/nginx.vhost.access.log;
    error_log /var/log/nginx/nginx.vhost.error.log;

    location /projectname {
        root /usr/share/nginx/html/projectname ;

        try_files $uri $uri/ /index.html?$args;
    }
}

Try this and it should work.

Upvotes: 2

Gupta
Gupta

Reputation: 10368

1: Open sudo vi /etc/hosts file in you Linux machine

2: 127.0.0.1 example.com www.example.com

3: Save and exit.

Upvotes: 0

Related Questions