wholly_cow
wholly_cow

Reputation: 977

Unable to reference static files on nginx + bootstrap

I have my nginx conf file with the static file location set as:

# Settings to by-pass for static files
location ^~ /static/  {
    # Example:
    # root /full/path/to/application/static/file/dir;
    root /opt/flaskapp/static/;
}

My template file has this:

<link href="/static/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="/static/bootstrap-responsive.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/static/bootstrap.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Though, when I run my flask app - bootstrap isn't loading any of the js :(

I have tried multiple combinations of locations and even tried using this in my nginx con file:

location /bootstrap.min.js { 
    alias /opt/flaskapp/static/bootstrap.min.js; 
}

I can access the js file via 127.0.0.1/bootstrap.min.js.

I'm sure I'm missing something stupid.

Thanks!

Upvotes: 1

Views: 3253

Answers (1)

Xavier Lucas
Xavier Lucas

Reputation: 2632

This is because you think that nginx will look for /opt/flaskapp/static/<file> in the filesystem while it looks at /opt/flaskapp/static/static/<file> because the URI is always appended to the local path (root) until you either :

  • Use rewrite to change the URI.
  • Map the location prefix or regex to a physical path using the alias directive.

So in your case you want the latter, and the right configuration is :

location ^~ /static/ {
    alias /opt/flaskapp/static/;
}

In your specific case, as the URI prefix is the same as the directory name, you can also simply change your local root to the parent directory (root /opt/flaskapp).

Upvotes: 1

Related Questions