Skip to content

Nginx as Web server

Using nginx as a web server to host websites. We will create a server block listening on port 80 inside of the http block.

Serve Static Content

Following server block is used to serve static content such as HTML, CSS, JavaScript, images, videos etc.

http {
server {
listen 80;
server_name howtocoder.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
}
  • listen 80; - port 80 to listen http requests.
  • server_name howtocoder.com; - name of domain/sub-domain.
  • location / - This line spacifies the route, in this case it is / route.
  • root /var/www/html; - This line specifies the root folder for serving static contents.
  • index index.html index.htm; - specifies the index files to serve.

Configuring Nginx to serve HTTPS requests.

Nginx can handle SSL/TLS encryption and decryption. If we wanted to serve over 443 the configuration will look like the following:

http {
server {
listen 80;
server_name howtocoder.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name howtocoder.com;
ssl_certificate /etc/nginx/ssl/howtocoder.com.crt;
ssl_certificate_key /etc/nginx/ssl/howtocoder.com.key;
location / {
root /var/www/html;
index index.html index.htm;
}
}
}

SSL certificate has a key and a certificate file. The fields ssl_certificate & ssl_certificate_key is used to set the same.

Content Compression

nginx can compress responses using gzip to reduce bandwidth usage and improve load times. Following is the configuration for enabling gzip compression for static files.

server {
.
.
location / {
.
.
gzip on;
gzip_types text/plain application/json application/javascript text/css;
gzip_min_length 256;
}
}