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 https://www.writebash.com.
Now I want when user goes to www.writebash.com/danie
, it will redirect to my another website www.danieblog.com
.
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).
You add the location /danie (or url path as you want) to the block server as in the code below.
location /danie { rewrite ^/danie(.*)$ https://www.danieblog.com/$1 redirect; }
After you finish adding, the entire virtual host configuration looks like this.
server { listen 80; server_name www.writebash.com; error_log /var/log/nginx/writebash.com.error.log; access_log /var/log/nginx/writebash.com.access.log; location / { # Your configuration for the root location … } location /danie { rewrite ^/danie(.*)$ https://www.danieblog.com/$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.
«« How to install latest Nginx on Debian 8How to install MariaDB 10.2 on CentOS 6 »»