Cara Install Nginx dengan Virtual Hosts dan Certificate SSL

Nginx (singkatan dari Engine-x) adalah server HTTP dan reverse proxy yang bebas, open source, kuat, berkinerja tinggi, dan dapat diukur, email dan server proxy TCP / UDP standar. Nginx mudah digunakan dan dikonfigurasi, dengan bahasa konfigurasi yang sederhana. Nginx sekarang menjadi perangkat lunak server web yang lebih disukai untuk memberdayakan situs-situs yang sarat muatan, karena skalabilitas dan kinerjanya.

Dalam artikel ini akan membahas cara menggunakan Nginx sebagai server HTTP, mengkonfigurasinya untuk melayani konten web, dan mengatur virtual host berbasis nama domain dan menginstal SSL, termasuk sertifikat yang ditandatangani sendiri di Ubuntu dan CentOS .

Cara Install Nginx Web Server

Pertama mulai dengan menginstal paket Nginx dari repositori resmi menggunakan manajer paket Anda seperti yang ditunjukkan.

Setelah paket Nginx diinstal, Anda perlu memulai layanan, aktifkan untuk memulai secara otomatis saat boot dan lihat statusnya, menggunakan perintah berikut. Perhatikan bahwa di Ubuntu, harus dimulai dan diaktifkan secara otomatis saat paket sudah dikonfigurasikan sebelumnya.

Start and Check Nginx Status

Start and Check Nginx Status

Pada titik ini, server web Nginx harus aktif dan berjalan, Anda dapat memverifikasi status dengan perintah netstat.

Check Nginx Port Status

Check Nginx Port Status

Jika sistem Anda memiliki firewall, Anda perlu membuka port 80 dan 443 untuk memungkinkan lalu lintas HTTP dan HTTPS, dengan menjalankan.

Metode ideal untuk menguji penginstalan Nginx dan memeriksa apakah itu berjalan dan dapat melayani halaman web adalah dengan membuka browser web dan menunjuk ke IP server.

Instalasi yang berhasil diindikasikan oleh layar berikut ini.

Check Nginx Web Page

Check Nginx Web Page

Cara Konfigurasi Nginx Web Server

File Konfigurasi Nginx berada pada directory /etc/nginx dan global konfigurasinya di  /etc/nginx/nginx.conf baik CentOS maupun Ubuntu.

Nginx terdiri dari modul yang dikendalikan oleh berbagai opsi konfigurasi, yang dikenal sebagai directivesdirective sederhana nya (dalam bentuk nama dan nilai-nilai diakhiri dengan ;) atau block ( memiliki instruksi tambahan tertutup menggunakan {}). Dan perintah blok yang berisi arahan lain disebut context.

Semua arahan secara komprehensif dijelaskan dalam Nginx documentation di situs web Nginx. Anda bisa merujuknya untuk informasi lebih lanjut.

How to Serve Static Content Using Nginx in Standalone Mode

At a foundational level, Nginx can be used to serve static content such as HTML and media files, in standalone mode, where only the default server block is used (analogous to Apache where no virtual hosts have been configured).

We will start by briefly explaining the configuration structure in the main configuration file.

If you look into this Nginx configuration file, the configuration structure should appear as follows and this is referred to as the main context, which contains many other simple and block directives. All web traffic is handled in the http context.

The following is a sample Nginx main configuration (/etc/nginx/nginx.conf) file, where the http block above contains an include directive which tells Nginx where to find website configuration files (virtual host configurations).

Nginx Configuration File

Note that on Ubuntu, you will also find an additional include directive (include /etc/nginx/sites-enabled/*;), where the directory /etc/nginx/sites-enabled/ stores symlinks to the websites configuration files created in /etc/nginx/sites-available/, to enable the sites. And deleting a symlink disables that particular site.

Based on your installation source, you’ll find the default website configuration file at /etc/nginx/conf.d/default.conf (if you installed from official NGINX repository and EPEL) or /etc/nginx/sites-enabled/default (if you installed from Ubuntu repositories).

This is our sample default nginx server block located at /etc/nginx/conf.d/default.conf on the test system.

A brief explanation of the directives in the above configuration:

  • listen: specifies the port the server listens on.
  • server_name: defines the server name which can be exact names, wildcard names, or regular expressions.
  • root: specifies the directory out of which Nginx will serve web pages and other documents.
  • index: specifies the type(s) of index file(s) to be served.
  • location: used to process requests for specific files and folders.

From a web browser, when you point to the server using the hostname localhost or its IP address, it processes the request and serves the file /var/www/html/index.html, and immediately saves the event to its access log (/var/log/nginx/access.log) with a 200 (OK) response. In case of an error (failed event), it records the message in the error log (/var/log/nginx/error.log).

Test Nginx Default Site

Test Nginx Default Site

To learn more about logging in Nginx, you may refer to How to Configure Custom Access or Error Log Formats in Nginx.

Instead of using the default log files, you can define custom log files for different web sites, as we shall look at later on, under the section “setting up name-based virtual hosts (server blocks)”.

How to Restrict Access to a Web Page with Nginx

In order to restrict access to your website/application or some parts of it, you can setup basic HTTP authentication. This can be used essentially to restrict access to the whole HTTP server, individual server blocks or location blocks.

Start by creating a file that will store your access credentials (username/password) by using the htpasswd utility.

As an example, let’s add user admin to this list (you can add as many users as possible), where the -c option is used to specify the password file, and the -B to encrypt the password. Once you hit [Enter], you will be asked to enter the users password:

Then, let’s assign the proper permissions and ownership to the password file (replace the user and group nginx with www-data on Ubuntu).

Baca Juga:  How to Change Your FTP Port

As we mentioned earlier on, you can restrict access to your webserver, a single website (using its server block) or specific directory or file. Two useful directives can be used to achieve this:

  • auth_basic – turns on validation of user name and password using the “HTTP Basic Authentication” protocol.
  • auth_basic_user_file – specifies the credential’s file.

As an example, we will show how to password-protect the directory /var/www/html/protected.

Now, save changes and restart Nginx service.

The next time you point your browser to the above directory (http://localhost/protected) you will be asked to enter your login credentials (username admin and the chosen password).

A successful login allows you to access the directory’s contents, otherwise you will get a a “401 Authorization Required” error.

How to Setup Name-based Virtual hosts (Server Blocks) in Nginx

The server context allows multiple domains/sites to be stored in and served from the same physical machine or virtual private server (VPS). Multiple server blocks (representing virtual hosts) can be declared within the http context for each site/domain. Nginx decides which server processes a request based on the request header it receives.

We will demonstrate this concept using the following dummy domains, each located in the specified directory:

  • wearetecmint.com – /var/www/html/wearetecmint.com/
  • welovelinux.com – /var/www/html/welovelinux.com/

Next, assign the appropriate permissions on the directory for each site.

Now, create a sample index.html file inside each public_html directory.

Next, create the server block configuration files for each site inside the /etc/httpd/conf.d directory.

Add the following server block declaration in the wearetecmint.com.conf file.

wearetecmint.com.conf

Next, add the following server block declaration in the welovelinux.com.conf file.

welovelinux.com.conf

To apply the recent changes, restart the Nginx web server.

and pointing your web server to the above addresses should make you see the main pages of the dummy domains.

Test Nginx Virtual Hosts Websites

Test Nginx Virtual Hosts Websites

Important: If you have SELinux enabled, its default configuration does not allow Nginx to access files outside of well-known authorized locations (such as /etc/nginx for configurations, /var/log/nginx for logs, /var/www/html for web files etc..).

Baca Juga:  Virtuozzo : RTNETLINK: Operation Not Supported

You can handle this by either disabling SELinux, or setting the correct security context. For more information, refer to this guide: using Nginx and Nginx Plus with SELinux on the Nginx Plus website.

How to Install and Configure SSL with Nginx

SSL certificates help to enable secure http (HTTPS) on your site, which is essential to establishing a trusted/secure connection between the end users and your server by encrypting the information that is transmitted to, from, or within your site.

We will cover how to create and install a self-signed certificate, and generate a certificate signing request (CSR) to acquire an SSL certificate from a certificate authority (CA), to use with Nginx.

Self-signed certificates are free to create and are practically good to go for testing purposes and for internal LAN-only services. For public-facing servers, it is highly recommended to use a certificate issued by a CA (for example Let’s Encrypt) to uphold its authenticity.

To create a self-signed certificate, first create a directory where your certificates will be stored.

Then generate your self-signed certificate and the key using the openssl command line tool.

Let’s briefly describe the options used in the above command:

  • req -X509 – shows we are creating a x509 certificate.
  • -nodes (NO DES) – means “don’t encrypt the key”.
  • -days 365 – specifies the number of days the certificate will be valid for.
  • -newkey rsa:2048 – specifies that the key generated using RSA algorithm should be 2048-bit.
  • -keyout /etc/nginx/ssl-certs/nginx.key – specifies the full path of the RSA key.
  • -out /etc/nginx/ssl-certs/nginx.crt – specifies the full path of the certificate.

Create SSL Certificate and Key for Nginx

Create SSL Certificate and Key for Nginx

Next, open your virtual host configuration file and add the following lines to a server block declaration listening on port 443. We will test with the virtual host file /etc/nginx/conf.d/wearetecmint.com.conf.

Then add the ssl directive to nginx configuration file, it should look similar to below.

Now restart the Nginx and point your browser to the following address.

Check Nginx SSL Website

Check Nginx SSL Website

If you would like to purchase an SSL certificate from a CA, you need to generate a certificate signing request (CSR) as shown.

You can also create a CSR from an existing private key.

Then, you need to send the CSR that is generated to a CA to request the issuance of a CA-signed SSL certificate. Once you receive your certificate from the CA, you can configure it as shown above.

Summary

In this article, we have explained how to install and configure Nginx; covered how to setup name-based virtual hosting with SSL to secure data transmissions between the web server and a client.

If you experienced any setbacks during your nginx installation/configuration process or have any questions or comments, use the feedback form below to reach us.


Di tulis oleh: