How to redirect to a custom url with nginx?

Member

by dana , in category: Third Party Scripts , 23 days ago

How to redirect to a custom url with nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 22 days ago

@dana 

To redirect to a custom URL with Nginx, you can use the rewrite directive in your server block configuration.


Here is an example of how to redirect all requests to a specific URL:

1
2
3
4
5
6
7
8
server {
    listen 80;
    server_name example.com;

    location / {
        rewrite ^/(.*)$ http://www.example.com/your-custom-url permanent;
    }
}


In this example, all requests to http://example.com will be redirected to http://www.example.com/your-custom-url with a permanent redirect (HTTP status code 301).


Remember to reload Nginx after making changes to the configuration file:

1
sudo systemctl reload nginx


Alternatively, you can use the return directive:

1
2
3
4
5
6
7
8
server {
    listen 80;
    server_name example.com;

    location / {
        return 301 http://www.example.com/your-custom-url;
    }
}


Both methods will redirect requests to the specified custom URL.