Reverse Proxy under Nginx
Preface
Recently, I was developing a project that used both Java’s Spring Boot and Python’s Flask. To ensure access under the same domain name, I used Nginx as a reverse proxy. It was relatively easy to configure when only one application was proxied, but with multiple applications, various interfaces started reporting errors. To prevent future pitfalls, I wrote this blog to document the most correct configuration.
The First Proxy
Main Application Interface
For applications developed with SpringBoot, pointing to the root directory of the domain name, proxy address http://127.0.0.1:9000。
1 | location / |
Static Files
If there is only one application, you can write it like this, it will only proxy files of the following formats.
1 | location ~* \.(gif|png|jpg|css|js|woff|woff2)$ |
The Second Proxy
Backend Interface
This is an application developed with Flask, pointing to the /query
directory, proxy address http://127.0.0.1:9099。
1 | location ^~ /query |
The preceding ^~
must be written, otherwise it can only point to the first level path of the proxy address, and the rest will not work at all.
Frontend Directory
There’s nothing much to say here, after setting the directory, it will automatically point to the index file.
1 | location /app |
If you have to say there’s a pitfall, see Difference between alias and root.
Frontend Static Files
Although it has been referenced to the root directory before, the static
directory has not been referenced. If accessed, it will directly point to the first proxy program, so we also need to reference it again.
1 | location ^~ /app/static/ |
The preceding ^~
must be written, otherwise accessing files will result in crazy 404s.
The Third Method
The first two methods work, but writing two feels a bit redundant. The frontend static files and static files are actually together, so we can merge them into one.
1 | location ^~ /app/ |
Adding /
after specifying the directory can directly guide to the entire folder.
Load Balancing
Load Address
If you’re afraid that a service will go down and want to have a more stable service, you can deploy the application on two servers simultaneously and use Nginx for load balancing.
1 | upstream fzjh |
weight
represents the weight, theoretically, the higher the weight, the greater the chance of being assigned to that server.
Static Files
Store a static resource on the Nginx server and use the following line of code to guide it.
1 | location ~* \.(gif|png|jpg|css|js|woff|woff2)$ |
Difference between alias and root
alias
1 | location /static/ |
In this case, Nginx will automatically go to the /www/your-path/static/
directory to find files.
root
1 | location /static/ |
In this case, Nginx will automatically go to the /www/your-path/static/static/
directory to find files, meaning it adds an extra layer.