» Rust: Build a REST API with Rocket » 3. Deployment » 3.2 Reverse Proxy with Nginx

Reverse Proxy with Nginx

At the moment, your endpoint url looks like this:

http://localhost:8000/books

Let's strip the port (:8000).

You can simply make the api server run on port 80 by changing the config file.

Port 80 and 443 are default ports for HTTP and HTTPS respectively. They don't show up in the URL.

@@ -1,5 +1,5 @@
 [app]
-port = 8000
+port = 80
 page_size = 5
 token_secret = "I_Love_LiteRank"
 token_hours = 48

Caution: You may need sudo cargo run to run on port 80. However, your application should not be run as root because it is not secure.

But what if you have multiple servers (such as an api server, web server, chat server and etc) running on a machine, and you want to expose all of them through port 80?

That's why you need reverse proxy.

Nginx config

Install nginx: https://nginx.org/en/docs/install.html

Suppose you have an api server running on port 8000, and a web server running on port 3000. Your can tune your Nginx config like this:

server {
    listen 80;

    server_name yourdomain.com;

    location /web {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Reload Nginx to apply the changes.

Then, you can make a request like this:

curl http://localhost/books
PrevNext