nginx location 404 not found nginx location 404 not found nginx nginx

nginx location 404 not found


The following erroneous block (in your case);

 location ^~ /test/ {     root /usr/share/nginx/public;     index index.html index.htm; }

is telling nginx to look for directory 'test' into the folder (root) /usr/share/nginx/public. If there's no 'test' folder in that root, it will return 404. To paliate to your problem, i suggest you try using alias instead of root. Like so:

 location ^~ /test/ {     alias /usr/share/nginx/public;     index index.html index.htm; }

Also, just for kicks, index directive can be set generally so you don't have to re-write it all the time... like so;

 server {     listen       80;     server_name  localhost;     root   /usr/share/nginx/html;     index  index.html index.htm;     error_page   500 502 503 504  /50x.html;     location / { }     location ~^/test/ {         alias /usr/share/nginx/public;     }     location = /50x.html {         root   /usr/share/nginx/html;     } }

One thing you should also consider... the more 'precise' the location block, the higher in your config it should reside. Like that location = /50x.html. In a perfect world, that would be set up top, right after the general server block settings.

Hope it helps.


Error caused by root directive

location ^~ /test/ {    root /usr/share/nginx/public;    index index.html index.htm;}

Fix with alias directive

 location ^~ /test/ {     alias /usr/share/nginx/public;     index index.html index.htm; }

Other Improvements

Extra tip: the index directive can be set so that you don't have to re-write it.

server {    listen       80;    server_name  localhost;    root   /usr/share/nginx/html;    index  index.html index.htm;    error_page   500 502 503 504  /50x.html;    location / { }    location ~^/test/ {        alias /usr/share/nginx/public;    }    location = /50x.html {        root   /usr/share/nginx/html;    }}

nginx matches Location blocks partly based on position in the config. Ideally, you would invert what you have now. The location block would be higher in nginx config. To that end, the location = /50x.html would also move up. Order is

  1. Exact match =
  2. Forward match ^~ /
  3. Case sensitive regex ~ /
  4. Case insensitive regex ~*
  5. Path match /

More about nginx location priority. Also, you can always review the official documentation. The nginx documentation for location block http://nginx.org/en/docs/http/ngx_http_core_module.html#location


when your app is vuejs,you need write like this,can prevent 404,pay attention to double /test/

   location ^~/test/ {       alias /usr/local/soft/vuejs/;       try_files $uri $uri/ /test/index.html;    }