Nginx Redirect URL With HTTP/1.1 301 Moved Permanently Header

How do I redirect old ugly urls such as with clean url – 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
$ curl -I

More information and links:

  1. HttpRewriteModule documentation.
  2. pcre(3) man page

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum