10

I want the directory index file in the root of my site to be index.html but within a subdirectory /foo I want it to be bar.html

i.e.

  • /index.html
  • /foo/bar.html

Also I want requests to /foo or /foo/ or /foo/:anything to resolve to bar.html

  • Why doesn't my location block /foo work?
  • How do I specify the location block for /foo ?

Here's the server definition:

server {
  listen  80;
  server_name  domain.tld;
  port_in_redirect off;

  location / {
    # ssl is terminated at our load bal
    if ($http_x_forwarded_proto != 'https') {
      rewrite ^ https://$host$request_uri? permanent;
    }

    root   /usr/share/nginx/mysite/public;
    index  index.html;
    add_header Cache-Control "public max-age=600";
    add_header "X-UA-Compatible" "IE=Edge,chrome=1";
    charset UTF-8;
  }

  # this location doesn't work  <<<<<<<<<<<<<<
  location /foo {
    root  /usr/share/nginx/mysite/public/foo;
    index  bar.html;
  }

  # set expiration of assets to 30d for caching
  location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
    root   /usr/share/nginx/mysite/public;
    expires 30d;
    add_header Cache-Control "public";
    log_not_found off;
  }
}

EDIT: I also had the following at the bottom of that server block.

error_page  404              /404.html;
location = /404.html {
  root   /usr/share/nginx/www;
}

# redirect server error pages to the static page /50x.html
error_page   500 502 503 504  /50x.html;
location = /50x.html {
  root   /usr/share/nginx/www;
}
Ade
  • 699
  • 3
  • 10
  • 21

1 Answers1

9

To have bar.html as index file use:

location /foo {
    index bar.html;
}

If you wish any request to /foo/anything end up in /foo/bar.html use this:

location = /foo {
    try_files /foo/bar.html =404;
}

location /foo/ {
    try_files /foo/bar.html =404;
}

In your location you have the wrong root directive.

In your config nginx end up looking for the file /usr/share/nginx/mysite/public/foo/foo/bar.html

sebix
  • 4,313
  • 2
  • 29
  • 47
Alexey Ten
  • 8,435
  • 1
  • 34
  • 36
  • Thanks. I got it to work eventually... I actually omitted two error page definitions (now added to the question). Your answer didn't work until I removed those. What's going on there? – Ade May 19 '14 at 10:55
  • 1
    WHat doesn't work? – Alexey Ten May 19 '14 at 11:14
  • I _was_ getting a 404 error at `/foo` if I **only** added `location / foo { index bar.html; }`. The error page locations were (I think) a red herring - I had to add the `root` definition back into your `/foo` block and now it's giving me `bar.html` as intended. – Ade May 19 '14 at 11:44
  • To simplify: the `root` path needs to be defined in every `location` block otherwise a 404 error is returned for that location. – Ade May 19 '14 at 11:54
  • 1
    Oh, I missed that you defined `root` inside `location /`. Just define it on server level once. See also http://wiki.nginx.org/Pitfalls#Root_inside_Location_Block. – Alexey Ten May 19 '14 at 11:56