Nginx redirect a location to another domain

SystemMen - How does nginx redirect a location to another domain? To do this, we only need 1-2 lines of configuration. However, this article will explain to you more about that.

The problem

One problem here is probably quite a lot of people have been or will be encountering. I have a website, my example is

Now I want when user goes to, it will redirect to my another website

As you know, the url /danie (ie url path) in nginx is configured in each location. The question is how does Nginx redirect a position to another domain?

Nginx redirect a location to another domain

Now, let’s look at how to set up a redirect to another domain in nginx.

You open the virtual host configuration file for your domain or open the file nginx.conf (if you configure the entire domain to this file).

nginx-redirect-a-location-to-another-domain Nginx redirect a location to another domain
Nginx redirect a location to another domain.

You add the location /danie (or url path as you want) to the block server as in the code below.

location /danie {
    rewrite ^/danie(.*)$$1 redirect;

After you finish adding, the entire virtual host configuration looks like this.

server {
    listen 80;

    error_log  /var/log/nginx/;
    access_log /var/log/nginx/;

    location / {
        # Your configuration for the root location

    location /danie {
        rewrite ^/danie(.*)$$1 redirect;

If you just copy paste the code above you can finish the work. But here, I want to explain that code more clearly.

  • rewrite: a command to change the URL returned to the client. For a simple understanding, the user wants a URL A, but through this rewrite command it will write URL A to URL B and return it to the user.
  • ^/danie: Get all url requests with url path starting with /danie.
  • (.*): . matches a single character. Does not matter what character it is, except newline. And * matches preceding match zero or more times. So (.*) means select everything.
  • $: indicates the end of the string.
  • redirect: a command to redirect the url path to a destination, the destination here may be another location or another domain.

So you can understand ^/danie(.*)$ is select all url requests with the url path starting with /danie, select any character and number and selecting until the end of the string.

Then rewrite the url and redirect to the target domain and return the results to the user.

Check your results

After you add the configuration, you can type the following command to make sure the configuration is not faulty.

nginx -t

And reload nginx service, in most cases, i only use reload instead of restart.

service nginx reload

Now try to access the url path configured above and see if the results have been redirected to the destination domain.

«« »»