In general, business requirements sometimes require two different projects to be deployed under the same server in different directories.
For example, http://domain:port/admin matches the admin project
For example, http://domain:port/react matches the React project
Let’s write a new server in nginx.conf;
server {
listen 6002;
server_name* *. * *. * *. * *;gzip on;
location /admin {
alias /projects/admin/;
# specify home page
index index.html;
# Automatic jump
autoindex on;
}
location /react {
alias /projects/react/;
# specify home page
index index.html;
# Automatic jump
autoindex on; }}Copy the code
Then close nginx
[root]# nginx -s stop
Copy the code
Restart the nginx
[root]# nginx -c /etc/nginx/nginx.conf
Copy the code
Conclusion:
Note the difference between root and alias in location.
# 错误写法,会报404
location /admin {
root /projects/admin/;
# specify home page
index index.html;
# Automatic jump
autoindex on;
}
location /react {
root /projects/react/;
# specify home page
index index.html;
# Automatic jump
autoindex on;
}
# When you visit http://***/admin
# root ==> is actually pointing to http://***/admin/projects/admin/
# alias ==> actually points to http://***/admin, which can be found at /projects/admin/ index.html
Copy the code
document:
In case of the
root
directive, full path is appended to the root including the location part, where as in case of thealias
directive, only the portion of the path NOT including the location part is appended to the alias.
Let’s say we have the config
location /static/ {
root /var/www/app/static/;
autoindex off;
}
Copy the code
In this case the final path that Nginx will derive will be
/var/www/app/static/static
Copy the code
This is going to return 404
since there is no static/
within static/
This is because the location part is appended to the path specified in the root
. Hence, with root
, the correct way is
location /static/ {
root /var/www/app/;
autoindex off;
}
Copy the code
On the other hand, with alias
, the location part gets dropped. So for the config
location /static/ {
alias /var/www/app/static/;
autoindex off;
}
Copy the code
the final path will correctly be formed as
/var/www/app/static
Copy the code