Nginx configuration: How to drop the query string on a rewrite

As a quick note, if you need to drop the query string when configuring an Nginx rewrite request, this syntax works:

rewrite ^/foo/bar.*$  /bar?  permanent;

The key is to use the ? character at the end of the URL/URI you are redirecting users to. That drops the query string, so the user will be redirected to the exact /bar URI.

For more information, see the Nginx rewrite module page.

Handling trailing slash characters with Nginx 301 redirects

As a quick Nginx configuration example, if you need to configure a 301 Redirect with Nginx, and you also need to account for trailing slash characters in the original URL, I can confirm that this solution works for me:

rewrite /foo/bar/baz/?$  /foo/bar/baz.html permanent;

This Nginx configuration line will forward both of these URIs to the new URI:

Nginx 301 redirect examples

Here's an example of how to do a 301 Redirect with Nginx:

rewrite /blog/Content/2/8/581 /blog/post/java/dos-batch-files-compile-run-java-program-create-jar-file permanent;

As you can see, Nginx uses the keyword permanent instead of 301.

I just did a few hundred of these on this devdaily.com website. I put them in a separate "redirects.conf" file, and included that file into my main nginx.conf file like this:

Apache RedirectMatch wildcard examples

Apache Redirect 301 FAQ: How can I redirect many old web pages using the Apache Redirect or RedirectMatch syntax and wildcard patterns (regex patterns)?

I'm currently trying to fix a lot of URLs that I more or less intentionally broke when I deleted the old "directory" portion of this website. In short, after removing the directory, no URL at "/Dir" work any more, so I have thousands of broken URLs (technically "URIs") that look like this:

Letting Google know about broken links I've fixed

Last night I spent some time going through my Google Webmaster's account, and found a listing of a large number of links I had broken on this website, largely because I removed the old, stale "directory" I had on this site. That was a Yahoo-style phonebook directory that made sense in 1999, but doesn't make much sense in 2011.

An Apache 301 redirect for a deleted directory

I recently reorganized the devdaily.com website, and as part of that, I deleted an entire directory at the root level that was named "/Dir". This was the "directory", where I had a Yahoo-like directory of links to applets, tutorials, CGI scripts, and so on, so I had thousands of web pages with URLs like these: