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:
- HttpRewriteModule documentation.
- pcre(3) man page
🐧 Get the latest tutorials on Linux, Open Source & DevOps via:
- RSS feed or Weekly email newsletter
- Share on Twitter • Facebook • 0 comments... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |