How to deploy SSL certificate for Nginx

Publish: 2016-01-04 | Modify: 2017-06-21

Nginx is a high-performance HTTP and reverse proxy server, as well as an IMAP/POP3/SMTP server. Now more and more integrated environments are using Nginx servers, such as Junge's LNMP one-click package, AMH hosting panel, OneinStack, etc. If you want to deploy an SSL certificate for your website for the sake of showing off (security), how should you proceed?

nginx_580

一、Apply for an SSL Certificate

Both StartSSL and WoSign in China offer free SSL certificates. Of course, there are also many paid options. If it's just a personal blog website, free ones are enough. You can refer to the article Applying for a Free WoSign SSL Certificate to apply for a free SSL certificate.

二、Prepare the Environment

Just having the certificate is not enough. You also need to set up a web server to put the certificate on. As mentioned above, LNMP one-click package, AMH hosting panel, and OneinStack all use Nginx as the web server. Install one of them.

三、Deploy SSL

The most critical step is here. First, you need to upload the SSL certificate from step one to a directory on the server. You can use WinSCP to upload the .crt and .key files to the /usr/local/nginx/conf/ssl/ directory. Find the host configuration file (usually in /usr/local/nginx/conf/vhost/xxx.conf) and use the vi editor to add the following lines within the server block:

listen 443 ssl;
ssl_certificate /usr/local/nginx/conf/ssl/www_xiaoz_me.crt;
ssl_certificate_key /usr/local/nginx/conf/ssl/www_xiaoz_me.key;

四、Open Port 443

HTTPS (SSL) requires using port 443. If your firewall (iptables) has not opened port 443, it may cause the website to be inaccessible. Please execute the following three statements:

vi /etc/sysconfig/iptables   ##Edit the configuration file
-A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT   ##(Allow port 80 through the firewall)
/etc/init.d/iptables restart   ##Restart the firewall

五、Restart Nginx Server

For Junge's LNMP, simply enter the command "lnmp nginx restart". For AMH, enter the command "amh nginx restart". Also, if you are using a StartSSL certificate, it will prompt for the certificate password during the restart of Nginx. If configured incorrectly, it may cause Nginx to fail to start. Please make relevant backups before modifying the host configuration file.

六、Configuration File Example

The following code is an example of coexistence between port 80 (http) and port 443 (https) for reference.

server
{
listen 80;
listen 443 ssl;
server_name www.xiaoz.me;
index index.html index.htm index.php;
root /home/wwwroot/www.xiaoz.me/;
#ssl on; comment this line out
ssl_certificate /usr/local/nginx/conf/ssl/www_iamle_com.crt;
ssl_certificate_key /usr/local/nginx/conf/ssl/www_iamle_com.key;
#Other configurations omitted
}

Comments