Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic Nginx reverse proxy to forwarding requests from host to virtual machine local server.

This idea came from I am trying to access the local server inside a virtual machine from the browser on the host machine. Maybe you would ask why did I not use the Nat network port forwarding? The primary reason is that I want to keep my config files to be consistent for all machines. So I don’t need to change its contents when using those configs on virtual machines. *Click* Nice

And the second reason is that when you run a server bound with localhost, you could not access it by the port forwarding from your host machine. You have to change its bound address to 0.0.0.0 when you want to access servers from the host.

For those reasons, I try to use the Nginx reverse proxy to forward the requests. And this config is a basic reverse proxy to achieve my demands. This one works when the virtual machine on bridged network mode. My host OS is Windows 10. The virtual machine is Ubuntu 20.04.

server {
    listen 80;
    listen [::]:80;

    server_name _;

    location /proxy/ {
        rewrite ^/proxy/?(.*)$ /$1 break;
        proxy_pass                  http://localhost:<port>/;
        proxy_set_header            X-Real-IP $remote_addr;
        proxy_set_header            Host localhost;
        proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass_request_headers  on;
    }
}

You need to install the Nginx to use this reverse proxy config. For example, when your virtual machine is running Ubuntu:

# Install the Nginx
$ sudo apt update
$ sudo apt install nginx nginx-doc
# Remove the default config file
$ sudo rm /etc/nginx/sites-enabled/default
# Create a new config file and copy the configs above into it
$ sudo vim /etc/nginx/sites-available/reverse-proxy
# Link to sites-enabled
$ sudo ln -s /etc/nginx/sites-available/reverse-proxy /etc/nginx/sites-enabled/reverse-proxy
# Test the configuration
$ sudo nginx -t
# Configure UFW for HTTP and HTTPS traffic
$ sudo ufw allow http
$ sudo ufw allow https
# And don't forget to allow the ssh connections
$ sudo ufw allow ssh
$ sudo ufw enable
# If no errors are reported, reload the new configuration
$ sudo nginx -s reload

And you can access the local server inside the virtual machine from your browser on the host machine now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment