Nginx – redirect all url’s to root (not show the HTML page in the URL?)

nginxrewrite

I need to turn my previous site running wordpress into a single page site. My site can only contain a landing page and I want all of the old URL's to 301 redirect to the root of my site.

I have this working, but not exactly how I'd prefer. Currently, everything is redirecting to mysite.com/index.html, but I want it directed directly to mysite.com.

Here's the redirect code I'm using in my location / {} tags:

try_files $uri $uri/ /index.php?q=$uri&$args;
            if ( $uri !~ ^/(index\.php|css|images|uploads|js|robots\.txt|favicon\.ico|wp-admin|launch|wp-login\.php|inc) ) {
                    rewrite ^ http://www.mysite.com/index.html permanent;
            }

That bit of code redirects everything except those specific directories and and files that I have listed. This way, I can still access my wp-admin directory to add content to WordPress, so when I do pull the switch later, I can switch the site back on and have all of the content updated and ready for launch.

If I remove the index.html from my redirect above, my site goes into a redirect loop. If I make the rewrite rule just point to /, then my site also goes into a redirect loop.

Can someone help me update that code so that index.html doesn't show int he browser window as the actual URL? I'd really like the actual URL to be www.mysite.com, not www.mysite.com/index.html.

EDIT:

What I really need, is to specify the root directory in my !~ statement. But if I add |/| it allows all files and subdirectories to be ignored… which means my redirect rule never gets called.

Can I specify only a root directory, and not include any of the files or subdirectories within that root directory? This way I can tell nginx not to redirect at / of my domain, but if it finds /index.html it will redirect to /.

Best Answer

I see two ways:

  • add |$ to regexp
  • set up a location = / and make it run /index.php on whatever PHP backend you use (probably by setting fastcgi_param SCRIPT_FILENAME .../index.php;
Related Topic