Difference between revisions of "Nginx as Reverse Proxy"

From PKC
Jump to navigation Jump to search
Ben>Admin
 
(57 intermediate revisions by 8 users not shown)
Line 1: Line 1:
The first place to learn Nginx can be found in this book<ref>eJonghe, D. (2017). NGINX cookbook : advanced recipes for operations(First edition. ed., pp. 1 online resource (1 volume)). Retrieved from https://go.oreilly.com/massachusetts-institute-of-technology-mit/library/view/-/9781492049098/?ar</ref>:
After [[PKC]] is set up on a machine, you might want to expose the localhost service to the external world. This is when you will need a [[wikipedia:reverse proxy|reverse proxy]] to present the service through a public Internet Protocol (IP) address.
 
Nginx is a reverse proxy software. The following content is assuming that you are running an Ubuntu distribution of Linux. The software vendor had created a free book, and it can be found here:<ref>{{:BOOK/NGINX Cookbook}}</ref>.


=Install Nginx=
=Install Nginx=
The following code can be copied and pasted to perform the task of installing Nginx on Ubuntu:<ref>Edward S., How to Set Up an Nginx Reverse Proxy, Retrieved from https://www.hostinger.com/tutorials/how-to-set-up-nginx-reverse-proxy/</ref>
The following code can be copied and pasted to perform the task of installing Nginx on Ubuntu:<ref>Edward S., How to Set Up an Nginx Reverse Proxy, Retrieved from https://www.hostinger.com/tutorials/how-to-set-up-nginx-reverse-proxy/</ref> For scripted installation, please refer to [[Install Nginx using bash script on Ubuntu]].
 
<syntaxhighlight>
<syntaxhighlight>
sudo apt-get update
sudo apt-get update
sudo apt-get install nginx -y
sudo apt-get install nginx -y
</syntaxhighlight>
To test the installation, make sure that your server's port 80 and 443 are open, and their respective '''sources'''<ref group="note">'''Source''': "Determines the traffic that can reach your instance. Specify a single IP address, or an IP address range in CIDR notation (for example, 203.0.113.5/32). If connecting from behind a firewall, you'll need the IP address range used by the client computers. You can specify the name or ID of another security group in the same region. To specify a security group in another AWS account (EC2-Classic only), prefix it with the account ID and a forward slash, for example: 111122223333/OtherSecurityGroup." '''text extracted from Amazon Web Service'''</ref> are set to <code>0.0.0.0/0</code>.
For [https://aws.amazon.com/amazon-linux-ami/ Amazon AMI Linux] distribution,
<syntaxhighlight>
sudo amazon-linux-extras install nginx1
</syntaxhighlight>
</syntaxhighlight>


Line 13: Line 23:
sudo unlink /etc/nginx/sites-enabled/default
sudo unlink /etc/nginx/sites-enabled/default
</syntaxhighlight>
</syntaxhighlight>
To configure Nginx for multiple hosts, please refer to this website<ref>https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-server-blocks-virtual-hosts-on-ubuntu-14-04-lts</ref>:


=Create the Reverse Proxy=
=Create the Reverse Proxy=
Line 18: Line 31:
<syntaxhighlight>
<syntaxhighlight>
cd /etc/nginx/sites-available
cd /etc/nginx/sites-available
</syntaxhighlight>
Use a text editor or copy a file with the following file name: <code>reverse-proxy.conf</code>.
For example:
<syntaxhighlight>
vi reverse-proxy.conf
</syntaxhighlight>
</syntaxhighlight>


Line 40: Line 46:
     listen 80;
     listen 80;
     location / {
     location / {
         proxy_pass http://127.0.0.1:9352;
         proxy_pass http://localhost:9352;
     }
     }
}
}
</syntaxhighlight>
</syntaxhighlight>


=Test Nginx and the Reverse Proxy=
=Setting up Nginx and the Reverse Proxy=
Activate the directives by linking to /sites-enabled/ using the following command:
Activate the directives by linking to /sites-enabled/ using the following command:
<syntaxhighlight>
<syntaxhighlight>
sudo ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf
sudo ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf
</syntaxhighlight>
</syntaxhighlight>
'''Note that this linking process should only be used for reverse-proxy.conf. If one tries to link another file, nginx will report error and fail to work.'''


First, verify the syntax of all the above content is legitimate:
First, verify the syntax of all the above content is legitimate:
Line 62: Line 70:


=Set up Let's Encrypt=
=Set up Let's Encrypt=
After setting up Nginx, one can consider setting up the free-of-charge Let's Encrypt certificate. The following instructions are modeled after this Medium article<ref>The Mightywomble, How to set up Nginx reverse proxy with let’s encrypt, Retried from:https://medium.com/@mightywomble/how-to-set-up-nginx-reverse-proxy-with-lets-encrypt-8ef3fd6b79e5</ref>:
After setting up Nginx, one can consider setting up the free-of-charge Let's Encrypt certificate. The following instructions are modeled after this Medium article<ref>The Mightywomble, How to set up Nginx reverse proxy with let’s encrypt, Retrived from:https://medium.com/@mightywomble/how-to-set-up-nginx-reverse-proxy-with-lets-encrypt-8ef3fd6b79e5</ref>:
(For installation on AMI Linux, please see this page [https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/SSL-on-amazon-linux-2.html#letsencrypt Tutorial: Configure SSL/TLS on Amazon Linux 2].
)
<syntaxhighlight>
<syntaxhighlight>
sudo add-apt-repository ppa:certbot/certbot
sudo add-apt-repository ppa:certbot/certbot
</syntaxhighlight>
Then, install the python3 certbot for Nginx.
<syntaxhighlight>
sudo apt install python3-certbot-nginx
sudo apt install python3-certbot-nginx
</syntaxhighlight>
</syntaxhighlight>
For AMI Linux:
<syntaxhighlight>
sudo yum install -y certbot python2-certbot-apache
</syntaxhighlight>
'''Note that one should just create a file in the <code>/etc/nginx/sites-enabled/</code> directory. Linking files from other directories could cause errors.'''
Then, install the python3 certbot for Nginx.
<syntaxhighlight>
cd /etc/nginx/sites-enabled/
</syntaxhighlight>
In this directory: <code>/etc/nginx/sites-enabled/</code> create the following file using a text editor or just copy a text file to this location with a name that is similar to this:<code>dev.example.com</code>
For example, if the name of your domain is <code>dev.thewiki.us</code>, then the file name should be: <code>dev.thewiki.us</code>.
Using <code>vi</code> as a text editor, your will type this in command line:
<syntaxhighlight> 
vi dev.thewiki.us.conf     
</syntaxhighlight> 
<syntaxhighlight>                                                 
server {
    server_name dev.thewiki.us;
    # The internal IP of the VM that hosts your Apache config
    set $upstream 127.0.0.1:9352;
        location / {
        proxy_pass_header Authorization;
        proxy_pass http://$upstream;
        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_http_version 1.1;
        proxy_set_header Connection “”;
        proxy_buffering off;
        client_max_body_size 0;
        proxy_read_timeout 36000s;
        proxy_redirect off;
    }
    listen 80;
}
</syntaxhighlight>
First, test if the above file passes the syntactical test:
<syntaxhighlight>
sudo nginx -t
</syntaxhighlight>
Then, you may run:
<syntaxhighlight>
sudo systemctl reload nginx
</syntaxhighlight>
==Run the Certbot to get the Let's Encrypt certificate==
The installation script<ref>[[Install Nginx using bash script on Ubuntu]]</ref> will take you up to this point. You should use a terminal application to conduct the following steps manually.
Before running the following statement, make sure that the domain names listed here have already had the relevant IP addresses properly associated with the domain names, such as <code>example.com</code>, and <code>dev.example.com</code>
<syntaxhighlight>
sudo certbot --nginx -d example.com -d dev.example.com
</syntaxhighlight>
===Reverse Proxy===
After succeeded in running the certbot program, files in /etc/nginx/conf.d/ will be updated. The file to pay attention to is the <code>domain_name.conf</code> file, in the case of <code>dev.example.com</code>, the file name should be: <code>dev.example.com.conf</code>.
Specifically, in the directory: <code>/etc/nginx/conf.d/</code> create the following file using a text editor or just copy a text file to this location with a name that is similar to this:<code>dev.example.com.conf</code>
For example, if the name of your domain is <code>example.com</code>, then the file name should be: <code>example.com.conf</code>.
Using <code>vi</code> as a text editor, your will type this in command line:
<syntaxhighlight> 
vi example.com.conf     
</syntaxhighlight> 
The following content can be copied and pasted into your <code>example.com.conf</code> file. The port number, in this example, <code>9352</code> should be replaced by the port number of your choice.
<syntaxhighlight>
server {
    root /var/www/html;
    server_name example.com www.example.com;
    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/thewiki.us/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/thewiki.us/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    location / {
      proxy_pass  http://localhost:9352;
    }
}
server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com;
    return 404; # managed by Certbot
    location / {
      proxy_pass  http://localhost:9352;
    }
}
</syntaxhighlight>
=Configure Nginx for larger file uploads=
For websites that must handle upload more than 2Mb in size, one must add the following entry to the file <code>/etc/nginx/nginx.conf</code><ref>Vivek Gite, Nginx: 413 – Request Entity Too Large Error and Solution, https://www.cyberciti.biz/faq/linux-unix-bsd-nginx-413-request-entity-too-large/</ref>:
<syntaxhighlight>
# set client body size to 50M #
client_max_body_size 50M;
</syntaxhighlight>
=Test you application=
After all the previous steps are successfully finished, yon can try to copy the following URL and test in a browser that is already connected to the Internet.
http://example.com
This should bring you directly to the application, and your browser should automatically switch to <code>https://example.com</code>. And a small lock should be displayed next to this URL, indicating that the reverse-proxy is working and automatically forwarding track through <code>https</code>, the encrypted protocol.


=References=
=References=
<References/>
<References/>
==Notes==
<References group="note"/>

Latest revision as of 01:39, 9 September 2021

After PKC is set up on a machine, you might want to expose the localhost service to the external world. This is when you will need a reverse proxy to present the service through a public Internet Protocol (IP) address.

Nginx is a reverse proxy software. The following content is assuming that you are running an Ubuntu distribution of Linux. The software vendor had created a free book, and it can be found here:[1].

Install Nginx

The following code can be copied and pasted to perform the task of installing Nginx on Ubuntu:[2] For scripted installation, please refer to Install Nginx using bash script on Ubuntu.

sudo apt-get update
sudo apt-get install nginx -y

To test the installation, make sure that your server's port 80 and 443 are open, and their respective sources[note 1] are set to 0.0.0.0/0.

For Amazon AMI Linux distribution,

sudo amazon-linux-extras install nginx1

Disable Default Virtual Host of Nginx

Then, try to unlink this existing link:

sudo unlink /etc/nginx/sites-enabled/default


To configure Nginx for multiple hosts, please refer to this website[3]:

Create the Reverse Proxy

Now go to the Nginx site-available directory

cd /etc/nginx/sites-available

Use a text editor or copy a file with the following file name: reverse-proxy.conf.

For example, use the text editor vi, you can type the following command:

vi reverse-proxy.conf


In the file, type in the following content. Please note that this configuration, especially the port number 9352 is a PKC specific specification.

server {
    listen 80;
    location / {
        proxy_pass http://localhost:9352;
    }
}

Setting up Nginx and the Reverse Proxy

Activate the directives by linking to /sites-enabled/ using the following command:

sudo ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf

Note that this linking process should only be used for reverse-proxy.conf. If one tries to link another file, nginx will report error and fail to work.

First, verify the syntax of all the above content is legitimate:

sudo service nginx configtest

Then, restart Nginx to kick it into action:

sudo service nginx restart

Set up Let's Encrypt

After setting up Nginx, one can consider setting up the free-of-charge Let's Encrypt certificate. The following instructions are modeled after this Medium article[4]: (For installation on AMI Linux, please see this page Tutorial: Configure SSL/TLS on Amazon Linux 2. )

sudo add-apt-repository ppa:certbot/certbot


Then, install the python3 certbot for Nginx.

sudo apt install python3-certbot-nginx

For AMI Linux:

sudo yum install -y certbot python2-certbot-apache


Note that one should just create a file in the /etc/nginx/sites-enabled/ directory. Linking files from other directories could cause errors.

Then, install the python3 certbot for Nginx.

cd /etc/nginx/sites-enabled/

In this directory: /etc/nginx/sites-enabled/ create the following file using a text editor or just copy a text file to this location with a name that is similar to this:dev.example.com For example, if the name of your domain is dev.thewiki.us, then the file name should be: dev.thewiki.us. Using vi as a text editor, your will type this in command line:

  
vi dev.thewiki.us.conf
                                                  
server {
    server_name dev.thewiki.us;
    # The internal IP of the VM that hosts your Apache config
    set $upstream 127.0.0.1:9352;
        location / {
        proxy_pass_header Authorization;
        proxy_pass http://$upstream;
        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_http_version 1.1;
        proxy_set_header Connection “”;
        proxy_buffering off;
        client_max_body_size 0;
        proxy_read_timeout 36000s;
        proxy_redirect off;
    }
    listen 80;
}


First, test if the above file passes the syntactical test:

 
sudo nginx -t

Then, you may run:

 
sudo systemctl reload nginx

Run the Certbot to get the Let's Encrypt certificate

The installation script[5] will take you up to this point. You should use a terminal application to conduct the following steps manually.

Before running the following statement, make sure that the domain names listed here have already had the relevant IP addresses properly associated with the domain names, such as example.com, and dev.example.com

sudo certbot --nginx -d example.com -d dev.example.com

Reverse Proxy

After succeeded in running the certbot program, files in /etc/nginx/conf.d/ will be updated. The file to pay attention to is the domain_name.conf file, in the case of dev.example.com, the file name should be: dev.example.com.conf.

Specifically, in the directory: /etc/nginx/conf.d/ create the following file using a text editor or just copy a text file to this location with a name that is similar to this:dev.example.com.conf For example, if the name of your domain is example.com, then the file name should be: example.com.conf. Using vi as a text editor, your will type this in command line:

  
vi example.com.conf

The following content can be copied and pasted into your example.com.conf file. The port number, in this example, 9352 should be replaced by the port number of your choice.

server {
    root /var/www/html;
    server_name example.com www.example.com;

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/thewiki.us/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/thewiki.us/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location / {
      proxy_pass  http://localhost:9352;
    }


}
server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com;
    return 404; # managed by Certbot

    location / {
      proxy_pass  http://localhost:9352;
    }
}

Configure Nginx for larger file uploads

For websites that must handle upload more than 2Mb in size, one must add the following entry to the file /etc/nginx/nginx.conf[6]:

# set client body size to 50M #
client_max_body_size 50M;

Test you application

After all the previous steps are successfully finished, yon can try to copy the following URL and test in a browser that is already connected to the Internet.

http://example.com

This should bring you directly to the application, and your browser should automatically switch to https://example.com. And a small lock should be displayed next to this URL, indicating that the reverse-proxy is working and automatically forwarding track through https, the encrypted protocol.

References

Notes

  1. Source: "Determines the traffic that can reach your instance. Specify a single IP address, or an IP address range in CIDR notation (for example, 203.0.113.5/32). If connecting from behind a firewall, you'll need the IP address range used by the client computers. You can specify the name or ID of another security group in the same region. To specify a security group in another AWS account (EC2-Classic only), prefix it with the account ID and a forward slash, for example: 111122223333/OtherSecurityGroup." text extracted from Amazon Web Service