Nginx Installation and Configuration
Recently deploying web sites, used nginx, here recording main related operations and configurations. To summarize, nginx is a high-performance http and reverse proxy server. For specific nginx understanding, see official website and Wikipedia, learn about it.
Related Commands
# Install nginx via yum
$ yum -y install nginx
# Start nginx service
$ nginx
# Reload nginx configuration
$ nginx -s reload
# Stop nginx service
$ nginx -s stop
Related Configurations
gzip
After enabling Gzip, it will compress data output to user browsers, reducing data volume transmitted over network, improving browsing speed.
Below shows basic gzip configuration information in nginx.conf file
# Gzip
# Enable gzip
gzip on;
# Minimum file size to enable gzip compression, files smaller than set value won't compress
gzip_min_length 1k;
# gzip compression level, 1-10, higher number compresses better but uses more CPU time, detailed explanation later
gzip_comp_level 2;
# File types to compress. javascript has multiple forms. Values can be found in mime.types file.
gzip_types text/plain application/javascript application/x-javascript text/css text/html application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
# Whether to add Vary: Accept-Encoding in http header, recommended to enable
gzip_vary on;
# Disable IE 6 gzip
gzip_disable "MSIE [1-6]\.";
For frontend static resource gzip, we can also adopt pre-compression solution, this way, for user requests, can serve faster, improve performance, like webpack can generate gz files when packaging frontend static resources. Here shows static gzip configuration item.
gzip_static on;
- Reverse Proxy
#Define a server, listening on port 80, configured domain is www.1991421.cn
server{
listen 80;
# using www domain to access the main website
server_name www.1991421.cn;
access_log /var/log/nginx/www.log
location / {
root /usr/www/website_root;
}
}
HTTP to HTTPS Forced Redirect
server {
listen 80;
server_name blog.alanhe.me;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
ssl on;
ssl_certificate "/etc/nginx/ssl/blog.alanhe.me/fullchain.cer";
ssl_certificate_key "/etc/nginx/ssl/blog.alanhe.me/blog.alanhe.me.key";
...
}
client_max_body_size
If reporting 413 (Request Entity Too Large)
error, need to pay attention to this configuration, default 1MB
.
- Modify as needed, if don’t want restriction, change to 0.
- client_max_body_size can be placed under server or location.
location / {
client_max_body_size 0;
}
/usr/share/nginx/html
Recommended hosting location for static resources placed here.
referrer Whitelist
valid_referers none *.1991421.cn 1991421.cn;
if ($invalid_referer) {
return 403;
}