Setting up nginx

Published on December 29, 2020

Installation

Install nginx:

apk add nginx

Configuration

Edit /etc/nginx/nginx.conf:

user nginx nginx;
worker_processes 1;

error_log /var/log/nginx/error_log info;

events {
	worker_connections 1024;
	use epoll;
}

http {
	include /etc/nginx/mime.types;
	default_type application/octet-stream;

	log_format main
		'$remote_addr - $remote_user [$time_local] '
		'"$request" $status $bytes_sent '
		'"$http_referer" "$http_user_agent" '
		'"$gzip_ratio"';

	client_header_timeout 10m;
	client_body_timeout 10m;
	client_max_body_size 50m;
	send_timeout 10m;

	connection_pool_size 256;
	client_header_buffer_size 1k;
	large_client_header_buffers 4 2k;
	request_pool_size 4k;

	gzip on;
	gzip_min_length 1100;
	gzip_buffers 4 8k;
	gzip_types text/plain;

	output_buffers 1 32k;
	postpone_output 1460;

	sendfile on;
	tcp_nopush on;
	tcp_nodelay on;

	keepalive_timeout 75 20;

	ignore_invalid_headers on;

	include /etc/nginx/sites-enabled/*;
}

Create the directories for the per-site configurations:

mkdir -p /etc/nginx/sites-available
mkdir -p /etc/nginx/sites-enabled

Edit /etc/nginx/sites-available/02_localhost:

server {
	listen 8000;
	listen [::]:8000;
	server_name localhost;

	root /var/www/localhost/htdocs;
	index index.html index.htm;
	error_page 404 /404.htm;

	location / {
	}

	location ~* ".(htm)$" {
		try_files $uri "${uri}l" =404;
	}
}

Edit /etc/nginx/sites-available/02_example.com:

server {
	listen 80;
	listen [::]:80;
	server_name .example.com;

	root /var/www/example.com/htdocs;
	index index.html index.htm;
	error_page 404 /404.htm;

	location / {
	}

	location ~* ".(htm)$" {
		try_files "${uri}l" =404;
	}
}

Create the symlinks to enable the per-site configurations:

ln -s /etc/nginx/sites-available/02_localhost /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/02_example.com /etc/nginx/sites-enabled/

Create the directories:

mkdir -p /var/www/localhost/htdocs
mkdir -p /var/www/example.com/htdocs

Edit /var/www/localhost/htdocs/index.htm and /var/www/example.com/htdocs/index.htm:

<html>
	<head>
		<title>Test</title>
	</head>

	<body>
		<p>Hello, world!</p>
	</body>
</html>

Allow TCP traffic on the HTTP port (80):

ufw allow http

Check whether the Nginx configuration is valid:

nginx -t

Start the service:

/etc/init.d/nginx start
rc-update add nginx

Check if Nginx is listening on the HTTP port (80):

netstat -anp | grep nginx

You should now be able to access your website from http://example.com. In addition, you can forward the port 8000 over SSH:

ssh -L 8000:localhost:8000 example.com

Then you can point your browser to http://localhost:8000.


If you like my work or if my work has been useful to you in any way, then feel free to donate me a cup of coffee. Any donation is much appreciated!