Beginner's question: redirecting /dir/index.html to /dir/

Igor Sysoev igor at sysoev.ru
Fri Sep 10 07:58:52 MSD 2010


On Thu, Sep 09, 2010 at 06:22:23PM -0400, ez77 wrote:

> Greetings,
> 
> I'm trying to send all .../dir/index.html requests to .../dir/ . I
> looked this up in forums but I'm only able to do it for the root
> directory:
> 
> [code]
> location / { 
>     root   /var/www/mysite;
>     index  index.html index.htm;
>     if ($request_uri = /index.html) {
>     rewrite ^ http://$host? permanent;
>     }   
> }
> [/code]
> 
> Some day I'll try to stop this copy-and-paste madness, but "in the
> meantime"... could someone please give me a hand? I would greatly
> appreciate it.

You may do it using:

-    if ($request_uri = /index.html) {
+    if ($request_uri ~ /index.html) {

However, using "if ($request_uri ..." means that you should use "location"
instead of "if". Nevertheless, the right configuration:

     location / {
         root   /var/www/mysite;
         index   index.html;
     }

     location ~ /index.html$ {
         rewrite ^ http://$host/? permanent;
     }

does not work, because "index index.html" redirects internally "/" to
"/index.html" and you will get endless loop with browsers.
However, you may avoid the internal redirect via try_files:

     location / {
         root       /var/www/mysite;
         try_files  $uri  ${uri}index.html  =404;
     }

     location ~ /index.html$ {
         rewrite ^ http://$host/? permanent;
     }


-- 
Igor Sysoev
http://sysoev.ru/en/



More information about the nginx mailing list