Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static website in nginx, wrong path for static files

I'm trying to use nginx to serve a static website that was given to me. Its folder structure is like this:

static_website/
    index.html
    www.example.com/
    resources.example.com/
    uploads.example.com/

The index.html file in the root is the one generated by httrack and it simply contains a redirect to www.example.com/index.html. Inside the folder www.example.com are all the html files, in the other two folders are the css, javascript and image files.

Here is the nginx configuration:

server {
    index index.php index.html index.htm;

    server_name example.com;

    location / {
        root /var/www/static_website/www.example.com;
        try_files $uri $uri/ =404;
        index index.html;
    }

}

I can navigate through the pages, but the css, javascript and image files are not loaded. The path to one of the css files inside the html is like this:

href="../resources.example.com/style.css"

The only way I managed to get this working was to have the have the url like this:

example.com/www.example.com/

This way, all the path are correct. I'd like to avoid this and have simply example.com. Is there a way to do this?

like image 523
Carlo Avatar asked Dec 28 '25 11:12

Carlo


1 Answers

It looks like the site was originally intended to operate with ugly URLs like //example.com/www.example.com/.

But the path-relative URIs for the resources should work just fine relative to /, you just need to provide a location block which matches /resources.example.com/.

For example:

location / {
    root /var/www/static_website/www.example.com;
    try_files $uri $uri/ =404;
    index index.html;
}
location /resources.example.com/ {
    root /var/www/static_website;
}

I originally commented that you should try this:

location ~ \.(css|js|jpg|png|svg)$ { 
    root /var/www/static_website;
}

Which achieves a similar goal, but Nginx will process prefix locations more efficiently that regular expression locations.

like image 146
Richard Smith Avatar answered Jan 01 '26 11:01

Richard Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!