0

The site I'm working on generates a URL like below for the CSS file.

www.example.com/ca/pub/static/version123/styles.css

It returns 404 because the version123 portion is dynamic and generated somehow, and there's no corresponding directory for it. I'm trying to see if I can configure Nginx so that the above URL fetches the same file this URL does.

www.example.com/ca/pub/static/styles.css

style.css is located at /pub/static/styles.css.

Nginx location blocks look like this so far.

location /ca/pub {
    alias /pub; # this seems to work

    # Supposed to remove the 'version123' portion but doesn't work
    location ~ ^/static/version {
        rewrite ^/static/(version\d*/)?(.*)$ /static/$2 last;
    }

}

The outer block directive seems to be working as I can load the CSS through www.example.com/ca/pub/static/styles.css. However, I'm not sure about the nested location. How do I configure it so that when I enter www.example.com/ca/pub/static/version123/styles.css in the browser, the CSS file is returned?

Also noticed that without ~, the configuration is invalid.

nginx: [emerg] location "^/static/version" is outside location "/ca/pub"
5
  • I have no idea what you're trying to achieve.
    – Tim
    Commented May 18, 2017 at 19:11
  • @Tim I added some words to the first two sentences, but I don't think it can be more clear. What is it that you don't understand?
    – laketuna
    Commented May 18, 2017 at 19:32
  • You haven't stated the problem you're trying to solve. I suspect you're trying to make a file available on two URLs, or a different URL from the path on the file system. If this is the case you could give the file path, the current URL, and the desired URL.
    – Tim
    Commented May 18, 2017 at 19:54
  • @Tim I rewrote it with file path and URLs!
    – laketuna
    Commented May 18, 2017 at 20:19
  • That makes more sense. I wonder if you can use a location that matches the url "location /ca/pub/static/version123" with just a root directive inside.
    – Tim
    Commented May 18, 2017 at 20:34

1 Answer 1

0

Your nested location is invalid as the ^ only matches URIs that begin with /static and all of these URIs begin with /ca/pub/static. Your rewrite statement is invalid for the same reason.

All you need is a rewrite statement that forms a new URI, from whatever follows the /version.../ string. It may be efficient to wrap this inside a location block so that the regular expression is only evaluated where necessary:

location /ca/pub {
    alias /pub;
}
location /ca/pub/static/version {
    rewrite /version\d*/(.*)$ /ca/pub/static/$1 last;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .