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 :
Show
I don't know if it's necessary to do this, then i configure my nginx in the following form:
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:
2. Cách Nginx cache
3. Một số tùy chọn và tham số cấu hìnhproxy_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/
proxy_cache_key: Định nghĩa key cho cache. Mặc định cấu hình với giá trị sau: server { # redirect from http to https # return 301 https://$host$request_uri; server { } # Only using some protocols, not use SSLv2, SSLv3 # request to webserver }
}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 { # redirect from http to https # return 301 https://$host$request_uri; server { } # Only using some protocols, not use SSLv2, SSLv3 # request to webserver }
}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:
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 { # redirect from http to https # return 301 https://$host$request_uri; server { } # Only using some protocols, not use SSLv2, SSLv3 # request to webserver }
}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 { # redirect from http to https # return 301 https://$host$request_uri; server { } # Only using some protocols, not use SSLv2, SSLv3 # request to webserver }
}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 DrivesNế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:
Ở đâ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. 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 RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl 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 { # redirect from http to https # return 301 https://$host$request_uri; server { } # Only using some protocols, not use SSLv2, SSLv3 # request to webserver }
}2. Sử dụng SSL Certificate miễn phí của Let’s EncryptVớ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 nginxlocation ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf|zip|rar|html|htm|pdf)$ { }
location / { }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:
Step4: Tệp tin cấu hình Nginx của site vnsys.vn sau khi lấy certificate
0 3. Cấu hình Apache web serverTrong 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 Để 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)
1 Trong bài viết này chúng ta sẽ sử dụng Nginx làm Reverse proxy cho Apache web server 1. Cài đặt và cấu hình Apache web serverHiệ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
2 Cấu hình Apache listen ở port 8080, chúng ta sẽ sử dụng port 80 cho Nginx reverse proxy.
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:
4 Tạo virtualhost “example.local”
5 Tạo home directory cho site example.local và thiết lập Apache owner cho home directory
6
7 2. Cấu hình sử dụng Nginx làm reverse proxyCà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
8 Trong tệp tin /etc/nginx/proxy_params, chúng ta làm rõ một số tham số:
– 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
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
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 RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl 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 RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl 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 RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl 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 RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl 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:
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ừ SourceCá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à nginxCà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
mkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example Tạo key với mã hóa RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key 4 Step2: Download Nginxmkdir -p /etc/nginx/ssl/example cd /etc/nginx/ssl/example Tạo key với mã hóa RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl rsa -in server.key -out server.key Enter pass phrase for server.key: writing RSA key 5 Step3: InstallingMộ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 RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl 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:
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 RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl 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 RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl 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 RSAopenssl genrsa -des3 -out server.key 2048 Quá trình tạo key yêu cầu nhập pass phraseEnter 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 passphareopenssl 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ảnStart 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 NginxGó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 packageopenssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt 0 Step2: updateTrong 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à 443Trong 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
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 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:
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 { # redirect from http to https # return 301 https://$host$request_uri; server { } # Only using some protocols, not use SSLv2, SSLv3 # request to webserver }
}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 { # redirect from http to https # return 301 https://$host$request_uri; server { } # Only using some protocols, not use SSLv2, SSLv3 # request to webserver }
}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. |