How to add Nginx rewrite rules using SSH

Are you looking for a way on how to add Nginx rewrite rules using SSH on an Ubuntu server?

How to add Nginx rewrite rule using SSH

Rewrite rules are used to tell the server to redirect users from one URL to another. This is useful for a variety of reasons, such as consolidating multiple pages into one or redirecting users to a different page based on their location.

Related: How to fix the ERR_TOO_MANY_REDIRECTS on Plesk

Steps to add Nginx rewrite rules using SSH

  1. Log in to your server using SSH.
  2. Then open the Nginx configuration file for your website. This file is usually located in the /etc/nginx/sites-available directory, and it may be named something like default or example.com. Use a text editor to open the file
sudo nano /etc/nginx/sites-available/example.com
  1. Scroll down to the server block in the configuration file. This is where you will add your rewrite rules.
  2. To add a rewrite rule, use the rewrite directive. This is an example of a basic rewrite rule that redirects users from example.com/old-page to example.com/new-page:
rewrite ^/old-page$ /new-page permanent;
  1. You can also use regular expressions in your rewrite rules. For example, to redirect all pages with a .php extension to their equivalent .html page, you can use a rule like this:
rewrite ^(.*).php$ $1.html permanent;
  1. Once you have added your rewrite rules, save the configuration file and exit your text editor.
  2. Now test your changes by running the following command:
sudo nginx -t

If the test passes, reload Nginx to apply your changes:

sudo systemctl reload nginx

And that’s it! You can also utilize this method to add rewrite rules for Rank Math on your Ubuntu server.

Disclosure: We may earn commission for purchases that are made by visitors on this site at no additional cost on your end. All information is for educational purposes and is not intended for financial advice. Read our affiliate disclosure.

Share this:

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *