1

I want every request for http://localhost/static/ to be directed to /usr/share/nginx/static.

For example, it the user requests http://localhost/static/style/style.css, I want the server to reply with the content of /usr/share/nginx/static/style/style.css.

This is my code (which does not work):

server {
  server_name http://localhost/;
  rewrite ^/static/(.*) /usr/share/nginx/$1 permanent;
}

And this is the main config file:

worker_processes 1;

events {
    worker_connections 200;
}

http {
    # Basic Settings
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Logging Settings
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Include Other Configs
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Update: I have a file named mysite.conf like this which does not rewrite the urls as i mentioned in the question.

location /static {
    root /usr/share/nginx/static;
}

1 Answers1

0

Replace

server_name http://localhost/;

by

server_name localhost;

Per https://nginx.org/en/docs/http/ngx_http_core_module.html#server_name after the server_name directive you put the server's name, not an URL.

Also rewrite is to do HTTP redirections, so instead of

rewrite ^/static/(.*) /usr/share/nginx/$1 permanent;

use:

location /static {
    root /usr/share/nginx;
}

See this other answer for another example: Use nginx to serve static files from subdirectories of a given directory

Patrick Mevzek
  • 10,995
  • 16
  • 38
  • 54
  • I don't know why but the code does not work. Please see the main configuration file. https://paste.ubuntu.com/p/sKsJYKwvjs/ (I upload a file named mycnf.conf in that directory which has the code you wrote) – Arman Malekzadeh Jul 06 '18 at 15:38
  • 1) Put configuration as text in your question and 2) "does not work" is not enough. You connect to the server? What response do you get ? What do you have in logfiles ? Etc... – Patrick Mevzek Jul 06 '18 at 15:39
  • A root directive in a location block is totally valid and will work, so this answer isn't incorrect, but it's important to note that if you are going to use root directives in location blocks you must include one in the parent server block first, before any location blocks. Otherwise non matching location blocks within this server will have no root. – miknik Jul 06 '18 at 20:55