Django hướng dẫn cài đặt ssl nginx

I want to setup ssl for nginx, my project is a django and i also use gunicorn as wsgi http server. I add following lines in my settings.py code :

CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True

I don't know if it's necessary to do this, then i configure my nginx in the following form:

upstream app_server {
    server 127.0.0.1:6000; // your gunicorn server
}
server {
    listen 80;
    server_name <name>;
    return 301 https://$host$request_uri;
}
server {
    
# listen 80;
    listen 443 default ssl;
    client_max_body_size 4G;
    server_name <name>;
    
# ssl                  on;
    ssl_certificate      /etc/nginx/ssl/ssl.crt;
    ssl_certificate_key  /etc/nginx/ssl/ssl.key;
    ssl_session_timeout  5m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers   on;
    keepalive_timeout 5;
# path for static files
    root /home/deploy/;
    location /static/ {
    }
    location /media/ {
    }
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
# proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_pass http://app_server;
    }
    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /home/deploy/static;
    }
}

nginx configure is correct i think because its redirect 80 to 443,but nothing happens, 80 request sent, then nginx redirect it to 443, but nothing happend, it can't connect to gunicorn or project.

what is the problem of my nginx? my nginx version nginx/1.0.15. i almost see al related topics and according to them my configuration is correct. can any one help me? should i do something with gunicorn? my certificate is self-signed, or what should i do?

Nginx – ngoài việc phục vụ trực tiếp static file cực kỳ hiệu quả, nó còn có thể phục vụ với vai trò là proxy hoặc web server. Ngoài ra, Nginx còn có thể đảm nhận vai trò caching static file khi nó đứng trước một application server.

Có một số điểm cần biết:

  • Nginx phục vụ trực tiếp static file cực kỳ nhanh, tuy nhiên nó cũng ảnh hưởng đến mặt hiệu suất xử lý của Nginx khi số lượng request tăng cao (cụ thể về CPU và RAM)
  • Nếu sử dụng nginx như static cache thì chỉ tốn về mặt lưu trữ dữ liệu cache (liên quan phần storage), và sử dụng rất ít hiệu suất của server (cụ thể về CPU và RAM), do application server không cần phải xử lý page khi client request, mà nginx cache server sẽ phản hồi trực tiếp nội dung đã lưu cache.
  • Để tăng hơn nữa khả năng phục vụ static file, chúng ta cần lưu trữ cache với storage mà có khả năng read/write cao hơn như ổ SSD. Để phục vụ các tệp tin như audio, video với dung lượng lớn chúng ta lưu trữ cache qua SAN, NAS hoặc qua mạng như glusterfs.

2. Cách Nginx cache

  • Một client request nội dung đến application server
  • Cache kiểm tra xem nội dung đã tồn tại chưa?
    • Nếu kiểm tra phản hồi chưa có bản lưu nội dung được cache, kết quả là thông tin MISS cache, khi đó nội dung sẽ được lấy từ application server.
    • Nếu kiểm tra mà nội dung đã được cache, khi đó kết quả thông tin HIT cache, khi đó nội dung sẽ trả trực tiếp đến client mà không cần contact với application server
  • Một lần nội dung được cache, nó sẽ tiếp tục được phục vụ từ cache cho đến khi cache expire, hoặc khi cache bị clear/purge

Django hướng dẫn cài đặt ssl nginx

3. Một số tùy chọn và tham số cấu hình

proxy_cache_path: Thiết lập vị trí lưu các cache file. Chúng ta thiết lập lưu trong đường dẫn /store/cache/example.com/

  • levels: Chị thì này dùng để thiết lập cách các cache file được lưu đến hệ thống tệp tin (hay là cấp độ tạo thư mục cho lưu cache file). Nếu không định nghĩa, cache file được lưu trực tiếp vào vị trí được định nghĩa. Nếu một số lượng lớn các tệp tin cache được lưu trực tiếp vào một thư mục, khi đó tốc độ truy cập đến tệp tin sẽ chậm đi. Vì vậy, chúng ta định nghĩa levels, ví dụ như trong cấu hình levels=1:2 nghĩa là thư mục được phân thành 2 cấp, khi đó cache file được lưu vào thư mục con của vị trí lưu cache, dựa trên mã md5 hashes.
  • keys_zone: dùng thiết lập shared memory zone cho lưu trữ cache keys và metadata. Một bản sao các keys trong memory sẽ làm cho Nginx nhanh hơn để xác định request nào là HIT hay MISS mà không phải truy cập xuống disk, mục đích tăng tốc độ check. Ở đây, chúng ta định nghĩa keys_zone với tên example.com. Với 1MB zone, có thể lưu trữ dữ liệu cho khoảng 8000 keys, vì thế mà chúng ta cấu hình 400MB, có thể lưu trữ đến 3200000 keys.
  • Inactive: Chỉ thị này được dùng để bảo nginx clear cache một số asset mà không được truy cập trong khoảng time được thiết lập mà không quan tâm đến là cache đó đã expire hay chưa. Inactive content khác với expire content. Nginx không tự động xóa nội dung mà đã expire được định nghĩa bởi một cache control header. Ở đây, chúng ta thiết lập inactive=10d (10 ngày). Mặc định inactive được thiết lập là 10 phút.
  • max_size: Thiết lập không gian disk tối đa mà nginx sử dụng để lưu cache. Nếu không định nghĩa, mặc định nó sử dụng toàn bộ không gian disk có sẵn để sử dụng cho việc lưu cache. Khi cache đạt đến giới hạn được định nghĩa, một tiến trình cache manager được sử dụng để remove các tệp mà được sử dụng gần nhất để đưa cache size về dưới giới hạn được định nghĩa.

proxy_cache_key: Định nghĩa key cho cache. Mặc định cấu hình với giá trị sau:

server {

listen 80;
server_name example.local;
rewrite ^(.*) https://example.local$1 permanent; 
# redirect from http to https

# return 301 https://$host$request_uri;
}
server {
listen 443;
server_name example.local;
root /var/www/example;
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf|zip|rar|html|htm|pdf)$ {
  expires 30d; # caching, expire after 30 days
}
access_log /var/log/nginx/nginx.local-access.log;
error_log /var/log/nginx/nginx.local-error.log;
ssl on;

# Only using some protocols, not use SSLv2, SSLv3
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_certificate /etc/nginx/ssl/example/server.crt;
ssl_certificate_key /etc/nginx/ssl/example/server.key;
location / {
    proxy_pass http://localhost:8080; 
# request to webserver
    include /etc/nginx/proxy_params;
} }

2

Chúng ta có thể thay thế giá trị các biến sử dụng trong định nghĩa key, tùy thuộc giá trị mong muốn. Ví dụ định nghĩa key cho cache như sau:

server {

listen 80;
server_name example.local;
rewrite ^(.*) https://example.local$1 permanent; 
# redirect from http to https

# return 301 https://$host$request_uri;
}
server {
listen 443;
server_name example.local;
root /var/www/example;
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf|zip|rar|html|htm|pdf)$ {
  expires 30d; # caching, expire after 30 days
}
access_log /var/log/nginx/nginx.local-access.log;
error_log /var/log/nginx/nginx.local-error.log;
ssl on;

# Only using some protocols, not use SSLv2, SSLv3
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_certificate /etc/nginx/ssl/example/server.crt;
ssl_certificate_key /etc/nginx/ssl/example/server.key;
location / {
    proxy_pass http://localhost:8080; 
# request to webserver
    include /etc/nginx/proxy_params;
} }

3

Khi đó key có kiểu giống như này: https://example.com/abc.jpg

proxy_cache_revalidate: Nếu chỉ thị này enable, Nginx xác minh nội dung cache hiện tại vẫn hợp lệ. Cái này cho phép tiết kiệm bandwidth bởi vì server chỉ gửi item đầy đủ nếu nó đã sửa đổi từ lần được khi lại trong header Last-Modified kèm theo tệp tin khi Nginx tổ chức cache nó.

proxy_cache_min_uses: Thiết lập số lần request một nội dung (item) của một client trước khi Nginx thực hiện cache nó. Mặc định giá trị proxy_cache_min_uses là 1.

proxy_cache_use_stale: Khi origin server down trong một khoảng thời gian (mà chưa refesh) gặp các mã lỗi 5xx, khi đó client request nội dung mà đã được cache từ nginx cache server nó sẽ vẫn nhận thông tin đã cache.

Để bật tính năng này, chúng ta cấu hình như sau:

location / {
    # ...
    proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
}

proxy_next_upstream: Chỉ định trường hợp nào một request sẽ được chuyển qua nginx cache server tiếp theo. Chúng ta chỉ định các trường hợp lỗi sau:

server {

listen 80;
server_name example.local;
rewrite ^(.*) https://example.local$1 permanent; 
# redirect from http to https

# return 301 https://$host$request_uri;
}
server {
listen 443;
server_name example.local;
root /var/www/example;
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf|zip|rar|html|htm|pdf)$ {
  expires 30d; # caching, expire after 30 days
}
access_log /var/log/nginx/nginx.local-access.log;
error_log /var/log/nginx/nginx.local-error.log;
ssl on;

# Only using some protocols, not use SSLv2, SSLv3
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_certificate /etc/nginx/ssl/example/server.crt;
ssl_certificate_key /etc/nginx/ssl/example/server.key;
location / {
    proxy_pass http://localhost:8080; 
# request to webserver
    include /etc/nginx/proxy_params;
} }

4

proxy_ignore_headers: Chỉ thị cho phép Nginx bỏ qua một số header. Ví dụ bỏ qua header Cache-Control và Set-Cookie

server {

listen 80;
server_name example.local;
rewrite ^(.*) https://example.local$1 permanent; 
# redirect from http to https

# return 301 https://$host$request_uri;
}
server {
listen 443;
server_name example.local;
root /var/www/example;
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf|zip|rar|html|htm|pdf)$ {
  expires 30d; # caching, expire after 30 days
}
access_log /var/log/nginx/nginx.local-access.log;
error_log /var/log/nginx/nginx.local-error.log;
ssl on;

# Only using some protocols, not use SSLv2, SSLv3
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_certificate /etc/nginx/ssl/example/server.crt;
ssl_certificate_key /etc/nginx/ssl/example/server.key;
location / {
    proxy_pass http://localhost:8080; 
# request to webserver
    include /etc/nginx/proxy_params;
} }

5

proxy_cache_methods: Chỉ thị cho phép một số method được cache, mặc định GET và HEAD luôn được phép.

proxy_cache_lock: Tùy bật tùy chọn này với giá trị “on”, nếu nhiều client cùng request đến một file mà hiện tại chưa cache, khi đó chỉ có request đầu tiên được phép thực hiện contact với origin server và sau đó nội dung sẽ được cache.

4. Splitting the Cache Across Multiple Hard Drives

Nếu có nhiều hard disk, chúng ta có thể tách vị trí lưu cache đến nhiều vị trí khác nhau. Ví dụ cấu hình sau:

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

Ở đây, chúng ta tách vị trí lưu cache ra 2 hard disk và lưu ở 2 key zone. Sử dụng khối cấu hình “split_clients” định nghĩa key zone chung với biến $my_cache cho 2 key zone và cho phép mỗi hard disk sẽ cache một nửa số lượng request (50%). MD5 hash dựa trên biến $request_uri để xác định cache nào được sử dụng cho mỗi request

Read more

https://www.nginx.com/blog/nginx-caching-guide/

Trong phần trước, mình có cấu hình Nginx làm reverse proxy cho Apache web server. Với giao thức http – một giao thức chưa được mã hóa. Để đảm bảo an toàn hơn trong giao tiếp giữa client và server qua trình duyệt, chúng ta cần cài đặt chứng chỉ SSL trên server.

Django hướng dẫn cài đặt ssl nginx

1. Tự tạo self-signed certificate

Đây là certificate mà ta sẽ tự tạo ra trên chính server. Certificate này không được xác thực bởi các nhà cung cấp chứng chỉ số.

Các bước tạo self-signed certificate và cấu hình Nginx sử dụng SSL như sau:

Step1: Tạo private key

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

Step2: Đăng ký certificate

openssl req -new -key server.key -out server.csr

Đăng ký certificate có thể như sau:

Country Name (2 letter code) [XX]:VN State or Province Name (full name) []:HN Locality Name (eg, city) [Default City]:HN Organization Name (eg, company) [Default Company Ltd]:Example Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server’s hostname) []:example.local Email Address []:

Step3: Tạo certificate

Dựa vào CSR ở trên, chúng ta tạo một self-signed certificate, với hiệu lực 365 ngày

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Step4: Cấu hình Nginx reverse proxy với SSL cho website example.local

Tạo hay sửa đổi tệp tin cấu hình site example.local với nội dung sau:

(vim /etc/nginx/sites-enabled/example.conf)

server {

listen 80;
server_name example.local;
rewrite ^(.*) https://example.local$1 permanent; 
# redirect from http to https

# return 301 https://$host$request_uri;
}
server {
listen 443;
server_name example.local;
root /var/www/example;
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf|zip|rar|html|htm|pdf)$ {
  expires 30d; # caching, expire after 30 days
}
access_log /var/log/nginx/nginx.local-access.log;
error_log /var/log/nginx/nginx.local-error.log;
ssl on;

# Only using some protocols, not use SSLv2, SSLv3
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_certificate /etc/nginx/ssl/example/server.crt;
ssl_certificate_key /etc/nginx/ssl/example/server.key;
location / {
    proxy_pass http://localhost:8080; 
# request to webserver
    include /etc/nginx/proxy_params;
} }

2. Sử dụng SSL Certificate miễn phí của Let’s Encrypt

Với self-signed certificate thì chúng ta chỉ sử dụng cho nội bộ công ty. Đối với website public mà cần độ tin tưởng từ người dùng, chúng ta cần phải sử dụng certificate được cung cấp từ CA (certificate authority) nào đó. Nếu là cá nhân hoặc để thử nghiệm website sử dụng SSL, chúng ta có thể sử dụng của Let’s Encrypt.

Let’s Encrypt là nhà cung cấp SSL miễn phí. Hiện tại thì Let’s Encrypt cho phép chúng ta đăng ký certificate miễn phí 3 tháng và sau đó yêu cầu renew.

Để lấy certificate từ Let’s Encrypt chúng ta sử dụng công cụ Certbot

Step1: Cài đặt Certbot

yum install python-certbot-nginx

Step2: Thông tin cấu hình Nginx khi chưa có SSL

Certbot có thể tự động cấu hình SSL cho Nginx, tuy nhiên điều kiện cần là nó cần xác định được cấu hình website đã tồn tại. Thông tin cấu hình cơ bản như sau cho site vnsys.vn (thay site vnsys.vn với tên site phù hợp chúng ta sử dụng)

server { listen 80; server_name vnsys.vn; root /var/www/vnsys;

Select files to be deserved by nginx

location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf|zip|rar|html|htm|pdf)$ {

  access_log        off;
  log_not_found     off;
  expires 30d; # caching, expire after 30 days
} location / {
    proxy_pass http://localhost:8080;
    include /etc/nginx/proxy_params;
}

Only allow GET and HEAD request methodsif ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; } }

Step3: Lấy một SSL Certificate

Certficate sẽ được xác thực qua internet đến CA, vì vậy yêu cầu sử dụng site public, trong trường hợp này ta sẽ lấy cert cho site vnsys.vn

certbot --nginx -d vnsys.vn

Thông tin lấy cert như sau:

Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator nginx, Installer nginx Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org Obtaining a new certificate Performing the following challenges: http-01 challenge for vnsys.vn Waiting for verification... Cleaning up challenges Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/vnsys.conf Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.


1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration.


Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2 Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/vnsys.conf


Congratulations! You have successfully enabled https://vnsys.vn You should test your configuration at: https://www.ssllabs.com/ssltest/analyze.html?d=vnsys.vn


IMPORTANT NOTES:

  • Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/vnsys.vn/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/vnsys.vn/privkey.pem

Step4: Tệp tin cấu hình Nginx của site vnsys.vn sau khi lấy certificate

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

0

3. Cấu hình Apache web server

Trong phần đầu của bài viết “https://vnsys.wordpress.com/2018/07/17/su-dung-nginx-lam-reverse-proxy-cho-apache-web-server/” cũng đã hướng dẫn cài đặt và cấu hình cơ bản Apache web server.

Sau khi cài đặt Apache với hướng dẫn cấu hình Apache như vậy, khi duyệt web và kiểm tra chúng ta thấy có lỗi mixed-content như hình dưới

Django hướng dẫn cài đặt ssl nginx

Để giải quyết mixed-content, cần báo cho Apache là chúng ta đang sử dụng giao thức https, khi Nginx reverse proxy đang phục vụ website mà sử dụng SSL

Thêm nội dung sau vào tệp tin cấu hình chính của Apache ( /etc/httpd/conf/httpd.conf)

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

1

Trong bài viết này chúng ta sẽ sử dụng Nginx làm Reverse proxy cho Apache web server

Django hướng dẫn cài đặt ssl nginx

1. Cài đặt và cấu hình Apache web server

Hiện tại bản mới của Apache web server là 2.4.xx, đã được tích hợp sẵn trong các repo cài đặt trên CentOS 7. Apache-2.4 hỗ trợ đầy đủ tính năng của Event MPM, ngoài ra Apache-2.4 sử dụng lượng memory thấp hơn so với Apache-2.2.

Cài đặt Apache

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

2

Cấu hình Apache listen ở port 8080, chúng ta sẽ sử dụng port 80 cho Nginx reverse proxy.

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

3

Thay đổi LogFormat, để Apache ghi nhận địa chỉ IP thực của agent từ Nginx, thay vì địa chỉ IP localhost (127.0.0.1). Sửa nội dung directive LogFormat trong tệp tin cấu hình httpd.conf với nội dung sau:

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

4

Tạo virtualhost “example.local”

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

5

Tạo home directory cho site example.local và thiết lập Apache owner cho home directory

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

6

  • Start & enable Apache

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

7

2. Cấu hình sử dụng Nginx làm reverse proxy

Cài đặt Nginx có thể tham khảo bài viết “Cài đặt Nginx từ source”

Hoặc cài đặt từ prebuild từ repo (mặc định đã support proxy): yum -y install nginx

2.1 Cấu hình các tham số chuẩn cho proxy

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

8

Trong tệp tin /etc/nginx/proxy_params, chúng ta làm rõ một số tham số:

  • proxy_set_header Host $host: Chúng ta dùng định nghĩa lại trường Host request header mà truyền đến backend khi mà cached được enable trên nginx . $host bằng giá trị server_name trong trường Host request header. Chúng ta thiết lập
  • proxy_set_header X-Real-IP: Truyền Real IP của client vào header khi gửi request đến Backend
  • proxy_set_header X-Forwarded-For: Mặc định client request thì thông tin sẽ chỉ giao tiếp với reverse proxy, vì vậy mà thông tin log của Backend server (Apache web server) sẽ chỉ nhận được là địa chỉ IP của Nginx proxy. Để ghi nhận địa chỉ IP thực của client vào backend web server, chúng ta sử dụng tham số: “proxy_set_header X-Forwarded-For”
  • proxy_set_header X-Forwarded-Proto: Xác định giao thức (http hoặc https) mà client gửi request tới proxy

– client_max_body_size: Thiết lập kích thước tối đa mà client sẽ gửi thông tin đến server

2.2 Reverse proxy cho example.local

  • Mở rộng thêm các tệp tin cấu hình

Thêm dòng sau vào trong khối http { } trong tệp cấu hình nginx.conf

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

Tạo thư mục chứa các tệp cấu hình Nginx mở rộng

proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m
                 max_size=10g inactive=60m use_temp_path=off;
proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m
                 max_size=10g inactive=60m use_temp_path=off;
split_clients $request_uri $my_cache {
              50%          “my_cache_hdd1”;
              50%          “my_cache_hdd2”;
}
server {
    # ...
    location / {
        proxy_cache $my_cache;
        proxy_pass http://my_upstream;
    }
}

9

– Tạo tệp tin cấu hình cho site example.local với nội dung sau:

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

0

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

1

Nginx phục vụ các tệp tin tĩnh nhanh hơn so với Apache. Vì vậy mà, trong tệp tệp tin example.conf ở trên, khi có request static file, Nginx sẽ trực tiếp phục vụ các yêu cầu đó, thay vì phải chuyển tiếp xử lý đến Apache.

– Tham số proxy_pass, dùng để thiết lập giao thức và địa chỉ của máy chủ backend và một URI tùy chọn mà một location sẽ được ánh xạ. Địa chỉ ở đây có thể là domain hoặc địa chỉ IP và một cổng tùy chọn. Trong trường hợp của chúng ta, Nginx phục vụ BackEnd có domain là example.local với port 8080. Trong nhiều trường hợp mà khả năng phân giải tên miền có vấn đề sẽ gây ra lỗi dịch vụ, vì vậy chúng ta nên ưu tiên sử dụng địa chỉ IP

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

2

– Enable reverse proxy for site example.local

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

3

Tại sao lại cài đặt Nginx từ source?

Bởi vì 2 lý do sau:

  • Thứ 1: Để hiểu cách cài đặt, bố trí vị trí cấu hình
  • Thứ 2:
  • Cài đặt Nginx từ gói Pre-Build giúp cài đặt nhanh, dễ dàng và bao gồm các module chính cần thiết nhưng nhược điểm không tích hợp sẵn các module mở rộng, có thể tiềm ẩn bug mà chưa được fix
  • Cài đặt từ source thì ngược lại với pre-build: Khó hơn, lâu hơn nhưng tận dụng tính năng mở rộng module (cái này cần thiết khi làm việc với hệ thống lớn, cần nhiều module khác nhau), tận dụng được tính năng mới nhất, bugfix và luôn up-to-date.

Trong phạm vi bài viết Nginx cài đặt từ nguồn trên CentOS 7

1. Cài đặt Nginx từ Source

Các bước cài đặt Nginx từ Source

Step1: Cài đặt các gói cần thiết cho biên dịch và nginx

Cài đặt các gói thư viện cho biên dịch, cũng như cái gói cần thiết cho các module mở rộng nginx

  • Thư viện PCRE cần cho module core và rewrite của nginx và hỗ trợ regular expressions (biểu thức chính quy)
  • Thư viện zlib: được yêu cầu từ module Gzip cho nén các header
  • Thư viện openssl: được yêu cầu cho module SSL để hỗ trợ giao thức HTTPS

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

4

Step2: Download Nginx

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

5

Step3: Installing

Một số tham số chính cần biết:

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

6

Để biết được các tham số sử dụng lệnh: ./configure –help

Quá trình cài đặt từ source gồm 3 bước:

  • ./configure (biên dịch)
  • make (kiểm tra quá trình biên dịch)
  • make install (cài đặt)

Trước khi cài đặt, tạo một user nginx dùng chạy dịch vụ nginx và không cho phép login server bằng câu lệnh

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

7

Biên dịch

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

8

Quá trình biên dịch (compile) diễn ra như sau:

mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example

Tạo key với mã hóa RSA

openssl genrsa -des3 -out server.key 2048

Quá trình tạo key yêu cầu nhập pass phrase

Enter pass phrase for server.key: Verifying - Enter pass phrase for server.key:

Chúng ta sẽ remove passphrase bỏ qua quá trình hỏi passphare

openssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key

9

Thực hiện cài đặt

openssl req -new -key server.key -out server.csr

0

Tổng kết quá trình cài đặt

make -f objs/Makefile install

make[1]: Entering directory `/opt/nginx-1.12.2′

test -d ‘/etc/nginx’ || mkdir -p ‘/etc/nginx’

test -d ‘/usr/sbin’ \

|| mkdir -p ‘/usr/sbin’

test ! -f ‘/usr/sbin/nginx’ \

|| mv ‘/usr/sbin/nginx’ \

‘/usr/sbin/nginx.old’

cp objs/nginx ‘/usr/sbin/nginx’

test -d ‘/etc/nginx’ \

|| mkdir -p ‘/etc/nginx’

cp conf/koi-win ‘/etc/nginx’

….

Step4: Start dịch vụ và kiểm tra một số thông tin cơ bản

Start nginx

openssl req -new -key server.key -out server.csr

1

Kiểm tra Nginx version

openssl req -new -key server.key -out server.csr

2

Kiểm tra trạng thái

openssl req -new -key server.key -out server.csr

3

Kết quả trả về:

Redirecting to /bin/systemctl status nginx.service

Unit nginx.service could not be found.

ở đây có nghĩa là hệ thống systemd chưa có tệp service cho nginx khi cài đặt từ source

Ta sẽ tạo tệp nginx.service cho hệ thống systemd

Tạo tệp /lib/systemd/system/nginx.service với nội dung như dưới đây:

openssl req -new -key server.key -out server.csr

4

Sau đó copy tệp nginx.service vào thư mục /lib/systemd/system/

Kiểm tra lại trạng thái nhé:

openssl req -new -key server.key -out server.csr

5

Note:

Nếu xảy ra lỗi với nginx.service thì kiểm tra đường dẫn pid của nginx (hiện tại đang để là /run/nginx.pid), thì ta sẽ cấu hình trong tệp nginx.conf cho đường dẫn pid về /run/nginx.pid

openssl req -new -key server.key -out server.csr

6

Ta để ý trong process nginx bao giờ cũng có 1 master và các worker (có nghĩa là có 1 người chủ và những người làm việc). Để ý lệnh dưới đây show ra các process, mà ở đó master sẽ do root vận hành, còn lại do người dùng nginx). Như ở dưới đây:

openssl req -new -key server.key -out server.csr

7

Khởi động nginx cùng hệ thống

openssl req -new -key server.key -out server.csr

8

Kiểm tra nginx đã hoạt động

openssl req -new -key server.key -out server.csr

9

2. Up-to-date Nginx

Gói pre-build thì quá trình nâng cấp cũng dễ hơn nhưng đừng lo lắng, gói source cũng dễ không kém. Ở đây là cài đặt lên bản mới, mà có thể là chỉ thêm tính năng cho bản cài đặt

Điểm chú ý nữa là Linux nó khác với Windows ở chỗ: update cũng không làm gián đoạn quá trình dịch vụ, không phải khởi động lại

Step1: Download lasted source package

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

0

Step2: update

Trong trường hợp dưới đây, chúng ta sẽ update bản từ nginx-1.10.2 lên nginx-1.12.2

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

1

3. Cấu hình firewall để mở port 80 và 443

Trong CentOS7, firewalld là dịch vụ firewall có sẵn và running

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

2

  • firewalld.service – firewalld – dynamic firewall daemon

Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)

Active: active (running) since Tue 2017-10-31 08:41:25 +07; 3h 1min ago

Docs: man:firewalld(1)

Main PID: 664 (firewalld)

CGroup: /system.slice/firewalld.service

└─664 /usr/bin/python -Es /usr/sbin/firewalld –nofork –nopid

Kiểm tra các port đang được chấp nhận đi qua firewalld

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

3

như vậy mặc định chỉ có mở service: dhcpv6 và ssh

Mở service http và https

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

4

Hoặc mở bằng port 80 và 443

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

5

Mở trình duyệt và kiểm tra Nginx

Django hướng dẫn cài đặt ssl nginx

Load balancing across multiple application instances is a commonly used technique for optimizing resource utilization, maximizing throughput, reducing latency, and ensuring fault-tolerant configurations.

Nginx is a very efficient HTTP load balancer to distribute traffic to several application servers and to improve performance, scalability and reliability of web applications.

Nginx Load balancing methods

The following load balancing mechanisms (or methods) are supported in nginx:

  • round-robin
  • least-connected
  • ip-hash

Django hướng dẫn cài đặt ssl nginx

nginx load balancing

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

6

Note: pointing nginx.vn to 10.11.218.250 (Replace nginx.vn with your real site name)

1. Default load balancing configuration (round-robin)

When load balancing method is not specifically configured, it defaults to round-robin. All requests are proxied to the server group, and nginx applies HTTP load balancing to distribute the requests.

Install Nginx on srv-lb01, see at http://vietsystem.blogspot.com

Create a new configuration file called /etc/nginx/sites-available/nginx.vn with the following contents:

vim /etc/nginx/sites-available/nginx.vn

# Defines a group of servers and Load balancing methods

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

7

Enable the site and restart Nginx

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

8

Open web browser and go to http://nginx.vn

2. Least connected load balancing

Least-connected load balancing is activated when the least_conn directive is used as part of the server group configuration:

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

9

3. ip hash load balancing

To configure ip-hash load balancing, just add the ip_hash directive to the server (upstream) group configuration

server {

listen 80;
server_name example.local;
rewrite ^(.*) https://example.local$1 permanent; 
# redirect from http to https

# return 301 https://$host$request_uri;
}
server {
listen 443;
server_name example.local;
root /var/www/example;
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf|zip|rar|html|htm|pdf)$ {
  expires 30d; # caching, expire after 30 days
}
access_log /var/log/nginx/nginx.local-access.log;
error_log /var/log/nginx/nginx.local-error.log;
ssl on;

# Only using some protocols, not use SSLv2, SSLv3
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_certificate /etc/nginx/ssl/example/server.crt;
ssl_certificate_key /etc/nginx/ssl/example/server.key;
location / {
    proxy_pass http://localhost:8080; 
# request to webserver
    include /etc/nginx/proxy_params;
} }

0

4. Weighted load balancing

When the weight parameter is specified for a server, the weight is accounted as part of the load balancing decision.

server {

listen 80;
server_name example.local;
rewrite ^(.*) https://example.local$1 permanent; 
# redirect from http to https

# return 301 https://$host$request_uri;
}
server {
listen 443;
server_name example.local;
root /var/www/example;
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf|zip|rar|html|htm|pdf)$ {
  expires 30d; # caching, expire after 30 days
}
access_log /var/log/nginx/nginx.local-access.log;
error_log /var/log/nginx/nginx.local-error.log;
ssl on;

# Only using some protocols, not use SSLv2, SSLv3
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_certificate /etc/nginx/ssl/example/server.crt;
ssl_certificate_key /etc/nginx/ssl/example/server.key;
location / {
    proxy_pass http://localhost:8080; 
# request to webserver
    include /etc/nginx/proxy_params;
} }

1

With this configuration, every 4 new requests will be distributed across the application instances as the following: 3 requests will be directed to srv-web01, one request will go to srv-web02, and another one to srv-web03.