Home

How to setup Nginx to serve a static site on a path different than root

11 Feb 2022 - Ronald

This article describes how to setup Nginx to serve a static site on a path different than root.

Let’s say you have already a website at mydomain.com, you are using Nginx as the web server and you want to set it up to serve static files from a path, let’s say domain.com/blog

What I did to solve this problem was to edit my Nginx configuration file at “/etc/nginx/sites-available/mydomain.com” and add the location /blog block inside the server block, as follows, assuming my static files are located in the server inside “/path/to/_site”:

server {

        if ($host = mydomain.com) {
            return 301 https://www.$host$request_uri;
        }

        root /var/www/mydomain.com/html;
        index index.html index.htm index.nginx-debian.html;

        server_name mydomain.com www.mydomain.com;

        location / {
                proxy_pass http://localhost:3000;
                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 /path/to/_site;
                index index.html;
                try_files $uri $uri/ =404;
        }

    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

That’s all!

Notice the use of alias. I use it becaue the path “/blog” doesn’t match the folder “_site” where my static files are in the server.

If your static files are in a path called “path/to/blog” then you can use root without including “blog” at the end:

        location /blog {
                root /path/to;
                index index.html;
                try_files $uri $uri/ =404;
        }

Meaning any HTTP request to mydomain.com/blog will serve the files at /path/to/blog.