在CentOS7上配置LNMP环境:Nginx篇

早就听说AWS的大名了,信用卡办下来后第一件事就是申请了个AWS的账号,买了美东的EC2(CentOS7)及RDS(MySQL5.6)资源各一。当然都是免费套餐中的,不管怎样总算是终于有了自己的主机了。

老规矩,初始化CentOS7,放上自己的key,配置好安全组打通EC2与RDS之间的网络,测试了下发现通了。

因为之前使用的GitHub Pages博客一直都是静态的Html,所以这次打算直接丢到EC2上先用nginx跑起来,然后将国外线路解析到这台EC2上,国内线路用 七牛的CDN 的,相册中的照片也是存贮在七牛的。

一步步来吧,先整个Nginx。

安装Nginx

1、安装Nginx依赖及常用软件包

[[email protected] opt]# yum -y install net-tools git gcc rsync  lrzsz telnet wget ntp dstat mlocate bind-utils nscd psmisc python-devel python-pip mtr chrony gcc gcc-c++ autoconf automake zlib zlib-devel openssl openssl-devel pcre-devel

2、安装前的准备

# 创建Nginx运行用户
[[email protected] opt]# groupadd -r www
[[email protected] opt]# useradd -s /sbin/nologin -g www -r www
# 获取Nginx源码并解压
[[email protected] opt]# wget http://nginx.org/download/nginx-1.11.12.tar.gz
[[email protected] opt]# tar xf nginx-1.11.12.tar.gz
[[email protected] opt]# cd nginx-1.11.12

3、编译安装Nginx

# 编译Nginx
[[email protected] nginx-1.11.12]# ./configure 
--prefix=/etc/nginx 
--sbin-path=/usr/sbin/nginx 
--conf-path=/etc/nginx/nginx.conf 
--error-log-path=/var/log/nginx/error.log 
--http-log-path=/var/log/nginx/access.log 
--pid-path=/var/run/nginx.pid 
--lock-path=/var/run/nginx.lock 
--http-client-body-temp-path=/var/cache/nginx/client_temp 
--http-proxy-temp-path=/var/cache/nginx/proxy_temp 
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp 
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp 
--http-scgi-temp-path=/var/cache/nginx/scgi_temp 
--user=www 
--group=www 
--with-http_ssl_module 
--with-http_realip_module 
--with-http_addition_module 
--with-http_sub_module 
--with-http_dav_module 
--with-http_flv_module 
--with-http_mp4_module 
--with-http_gunzip_module 
--with-http_gzip_static_module 
--with-http_random_index_module 
--with-http_secure_link_module 
--with-http_stub_status_module 
--with-http_auth_request_module 
--with-mail_ssl_module 
--with-file-aio 
--with-cc-opt='-O2 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic'
# 安装Nginx
[[email protected] nginx-1.11.12]# make && make install
# 查看Nginx版本以确认Nginx安装成功
[[email protected] nginx-1.11.12]# nginx -V
# 创建Nginx缓存目录并赋予相应权限
[[email protected] nginx-1.11.12]# mkdir -p /var/cache/nginx/{client_temp,proxy_temp,fastcgi_temp,uwsgi_temp,scgi_temp}
[[email protected] nginx-1.11.12]# chown -R www.www /var/cache/nginx/
# 将Nginx添加到systemd中
[[email protected] nginx-1.11.12]# vi /usr/lib/systemd/system/nginx.service 
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
  
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.conf
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
  
[Install]
WantedBy=multi-user.target
# 设置nginx开机启动并启动
[[email protected] opt]# systemctl enable nginx.service
[[email protected] opt]# systemctl start nginx.service
# 确认nginx进程已启动
[[email protected] opt]# ps -ef|grep nginx
root     12245     1  0 4月05 ?       00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
www      19228 12245  0 15:02 ?        00:00:00 nginx: worker process
root     29996 29890  0 16:58 pts/3    00:00:00 grep --color=auto nginx

这时候浏览器访问 http:// ,如果 安全组firewalldselinux 配置正确的话访问的应该是 nginx 的默认页。

4、Nginx 虚拟主机 配置

是时候放网站了。网站放置前需要把相应的 域名解析 到这台EC2上,或者就需要 绑定本地hosts 。这里是将国外线路 A记录 到这台 EC2 上,同时添加了个 a.opstrip.com 域名指向这台 EC2

[[email protected] opt]# git clone https://github.com/opstrip/opstrip.github.io.git      # 克隆GitHub Pages博客中的Html源码
[[email protected] opt]# ln -s /opt/opstrip.github.io /usr/share/html
[[email protected] opt]# mkdir -p /etc/nginx/conf.d                                      # 将Nginx虚拟机配置文件放入到此目录
[[email protected] opt]# vi /etc/nginx/nginx.conf                                        # Nginx主配置文件
    
user  www;
worker_processes  1;
    
error_log  /var/log/nginx/error.log;
error_log  /var/log/nginx/error.log  notice;
error_log  /var/log/nginx/error.log  info;
    
pid        /var/run/nginx.pid;
    
events {
    use epoll;
    worker_connections 51200;
    multi_accept on;
}
    
http {
    include       mime.types;
    default_type  application/octet-stream;
    
    #log format
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" $http_x_forwarded_for';
                      
    access_log  /var/log/nginx/access.log  main;
    
    server_names_hash_bucket_size 128;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 50m;
    
    sendfile on;
    tcp_nopush     on;
    keepalive_timeout 60;
    tcp_nodelay on;
    
    # fastcgi_connect_timeout 300;
    # fastcgi_send_timeout 300;
    # fastcgi_read_timeout 300;
    # fastcgi_buffer_size 64k;
    # fastcgi_buffers 4 64k;
    # fastcgi_busy_buffers_size 128k;
    # fastcgi_temp_file_write_size 256k;
    
    gzip on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types       text/plain application/x-javascript text/css application/xml;
    gzip_vary on;
    gzip_proxied        expired no-cache no-store private auth;
    gzip_disable        "MSIE [1-6].";
    
    #limit_conn_zone $binary_remote_addr zone=perip:10m;
    ##If enable limit_conn_zone,add "limit_conn perip 10;" to server section.
    server_tokens off;
    
    #server {
        #listen       80;
        #server_name  localhost;
    
        #charset koi8-r;
    
        #access_log  logs/host.access.log  main;
    
        #location / {
            #root   html;
            #index  index.html index.htm;
        #}
    
        #error_page  404              /404.html;
    
        # redirect server error pages to the static page /50x.html
        #
        #error_page   500 502 503 504  /50x.html;
        #location = /50x.html {
            #root   html;
        #}
    
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
    
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ .php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
    
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {
        #    deny  all;
        #}
    #}
    
    
    # another virtual host using mix of IP-, name-, and port-based configuration
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
    
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    
    # HTTPS server
    
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
    
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
    
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
    
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;
    
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    include conf.d/*.conf;
}
[[email protected] opt]# vi /etc/nginx/conf.d/opstrip.conf
server {
    listen 80;
    listen [::]:80 ssl ipv6only=on; 
    server_name  opstrip.com www.opstrip.com a.opstrip.com;
    
    #charset koi8-r;
    
    #access_log  logs/host.access.log  main;
    root /usr/share/html;
    index index.html index.htm README README.txt;
    location / {
        root   /usr/share/html;
        index  index.html index.htm;
    }
    
    error_page  404              /404.html;
    
    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}
[[email protected] opt]# systemctl reload nginx

本地ping下 a.opstrip.com ,如果DNS已经生效用浏览器打开http://a.opstrip.com博客就可以展现出来了。

5、使用Let‘s encrypt免费证书

git clone https://github.com/letsencrypt/letsencrypt
cd letsencrypt/
./certbot-auto certonly --webroot --agree-tos -v -t --email [email protected] -w /usr/share/html -d opstrip.com,www.opstrip.com,a.opstrip.com

以上命令使用 certbotwebroot 方式获取, -w 表示网站路径, -d 表示域名,可以多个。遗憾的是还不支持泛域名。

由于机器是在墙外,只要DNS解析没问题,很容易就能通过验证。验证成功会返回类似如下信息:

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at
   /etc/letsencrypt/live/opstrip.com/fullchain.pem. Your cert will
   expire on 2017-07-04. To obtain a new or tweaked version of this
   certificate in the future, simply run certbot-auto again. To
   non-interactively renew *all* of your certificates, run
   "certbot-auto renew"
 - If you like Certbot, please consider supporting our work by:
           
   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

每次获取的证书有效期都是90天,不过到期后可以续签的。证书文件在 /etc/letsencrypt/live 下, fullchain.pemprivkey.pemnginx公钥私钥 。所以Nginx SSL配置如下:

[[email protected] opt]# vi /etc/nginx/conf.d/opstrip.conf
server {
    listen 80;
    listen [::]:80 ssl ipv6only=on; 
    server_name  opstrip.com www.opstrip.com a.opstrip.com;
    
    #charset koi8-r;
    
    #access_log  logs/host.access.log  main;
    root /usr/share/html;
    index index.html index.htm README README.txt;
    location / {
        root   /usr/share/html;
        index  index.html index.htm;
    }
    
    error_page  404              /404.html;
    
    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}
    
# HTTPS server
    
server {
    listen 443 ssl;
    listen [::]:443 ssl ipv6only=on;
    server_name  opstrip.com www.opstrip.com a.opstrip.com;
    
    ssl on;
    #ssl_certificate      /etc/nginx/certs/www.opstrip.com.pem;
    #ssl_certificate_key  /etc/nginx/certs/www.opstrip.com.key;
    ssl_certificate      /etc/letsencrypt/live/opstrip.com/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/opstrip.com/privkey.pem;
    
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
    
    #ssl_ciphers  HIGH:!aNULL:!MD5;
    #ssl_prefer_server_ciphers  on;
    
    root /usr/share/html;
    index index.html index.htm README README.txt;
    location / {
        root   /usr/share/html;
        index  index.html index.htm;
    }
}
[[email protected] opt]# systemctl reload nginx

现在可以访问 https://a.opstrip.com 了,如下图:

可以看到证书的颁发机构为 Let's Encrypt ,有效期 三个月

因此我们可以写脚本 自动续签 的,如下:

[[email protected] ~]# vi /opt/letsencrypt/renewletsencrypt.sh 
#!/bin/bash
    
. /etc/profile
    
# /usr/bin/systemctl stop nginx
cd /opt/letsencrypt
./letsencrypt-auto renew --email [email protected] --agree-tos
sleep 3
/usr/bin/systemctl reload nginx
exit 0
# 将脚本添加到crontab任务每3月执行一次即可
[[email protected] ~]# vi /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
    
# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
59 23 30 */3 * /bin/bash /opt/letsencrypt/renewletsencrypt.sh  >> /opt/letsencrypt/renewletsencrypt.out 2>&1

以上,Nginx及SSL证书自动获取讲解完成。下次将介绍PHP。

稿源:石尧的博客 (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » 在CentOS7上配置LNMP环境:Nginx篇

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录