≡ Menu

Nginx Redirect URL With HTTP/1.1 301 Moved Permanently Header

How do I redirect old ugly urls such as http://example.com/store/view.jsp?product=foo with clean url – http://example.com/store/view/product/foo using nginx reverse proxy?

You need to use HttpRewriteModule under nginx web server. This module makes it possible to change URI using regular expressions (PCRE), and to redirect and select configuration depending on variables. The syntax is as follows to chage URI in accordance with the regular expression and the replacement string.

rewrite regex replacement flag

Please note that directives are carried out in order of appearance in the configuration file. Here is sample configuration for the same:

# rewrite urls
rewrite ^/store/view/product/(.*) /store/view.jsp?product=$1  permanent;
## Uncomment the following line to redirect old urls with HTTP/301 ##
# rewrite "^/store/view.jsp?product=(.*)$" ^/store/view/product/$1 permanent;

Here is another example with try_files directive which checks for the existence of files in order, and returns the first file that is found:

### Add inside server { ... } directive block ###
### Only works with Nginx version 0.7.65+ ###
        location / {
                index store.php;
                try_files $uri $uri/ @ourcleanurls;
        # rewrite urls #
        location @ourcleanurls {
                rewrite ^/media/(.*) /includes/cache/helper.php?m=$1&images=1 last;
                rewrite ^/css/(.*) /includes/cache/helper.php?m=$1&css=1 last;
                rewrite ^/js/(.*) /includes/helper.php?m=$1&js=1&c=false last;
                rewrite ^/(.*) /store.php?pid=$1 last;

You need to reload the nginx server using the following command:
# /usr/local/nginx/sbin/nginx -s reload

How Do I Test New Changes?

You can use the curl command to test new changes including HTTP/1.1 301 Moved message:
$ curl -I http://example.com/store/view/product/foo
$ curl -I http://example.com/store/view.jsp?product=foo

More information and links:

  1. HttpRewriteModule documentation.
  2. pcre(3) man page
Share this tutorial on:

Like this? Follow us on Twitter OR support us by using Patreon

{ 0 comments… add one }
Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">

   Tagged with: , , , , , , , , , , ,