Install and Config Nginx Server on Ubuntu Server 18.04.1

Install Nginx on Ubuntu Server

tuenhai@ubuntu:~$ sudo apt update
tuenhai@ubuntu:~$ sudo apt insatll nginx

Adjust the firewall

tuenhai@ubuntu:~$ sudo ufw app list
tuenhai@ubuntu:~$ sudo ufw allow 'Nginx Full'
tuenhai@ubuntu:~$ sudo ufw status

Make sure the Nginx service is running by typing:

tuenhai@ubuntu:~$ systemctl status nginx

Navigate to server ip address will show: "Welcome to nginx!", it seems the server started automatically

Manage teh Nginx process

tuenhai@ubuntu:~$ sudo systemctl stop nginx
tuenhai@ubuntu:~$ sudo systemctl start nginx
tuenhai@ubuntu:~$ sudo systemctl restart nginx
tuenhai@ubuntu:~$ sudo systemtl reload nginx
tuenhai@ubuntu:~$ sudo systemctl enable nginx
tuenhai@ubuntu:~$ sudo systemctl disable nginx

Set nginx.conf bucket

tuenhai@ubuntu:~$ sudo vi /etc/nginx/nginx.conf

server_names_hash_bucket_size 128;
server_tokens off;

Reload config without nginx restart

tuenhai@ubuntu:~$ nginx -t
tuenhai@ubuntu:~$ nginx -s reload

How to Config Ubuntu Nginx Server

To see the default server block and help links

tuenhai@ubuntu:~$ cat /etc/nginx/sites-available/default

Create Serve Block:

tuenhai@ubuntu:~$ sudo touch /etc/nginx/sites-available/
tuenhai@ubuntu:~$ sudo vi /etc/nginx/sites-available/

Note: www/public directory permision should be 755

tuenhai@ubuntu:~$ sudo ln -s /etc/nginx/sites-availabe/ /etc/nginx/sites-enabled/
tuenhai@ubuntu:~$ sudo rm /etc/nginx/sites-enabled/default

How to prevent processing requests with undefined server names

If requests without the “Host” header field should not be allowed, a server that just drops the requests can be defined:

server {
    listen      80;
    return      444;

About privilige

Check to make sure the www/public dir has right permissions, it is 755 in my test

tuenhai@ubuntu:~$ ls -l

Public_html: 755

find . -type d -exec chmod 755 {} \;
find . -not -type d -exec chmod 644 {} \;
find . -type d -print0 | xargs -0 chmod 755
find . -not -type d -print0 | xargs -0 chmod 644
find . -type f -name "*.sh" -print0 | xargs -0 chmod 700

Globally disabling css image access logging for all sites:

  • Create file /etc/nginx/exclude_files.conf with content as bellow:

    location ~* .(css|js|png|jpg|jpeg|gif|ico|woff|woff2|otf|ttf|eot|svg|txt|webp|asp|php)$ { access_log off; log_not_found off; expires max; add_header Pragma public; add_header Cache-Control "public"; add_header Vary "Accept-Encoding"; }

  • Include exclude_files.conf in every server config

    server { # ... include exclude_files.conf; }

Nginx redirect sub domains to sub directories

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name ~^(?<sub>lixing|100-ke-xue-wen-ti|jiaoyu|sheng-wu-xue-si-xiang|xdl|zhong-yi-you-du|wintips|linuxtips)\.tuenhai\.com$;
    return 301 "${sub}${uri}";
任何人生疑惑,请找 海云青飞