nginx 服務器搭建
前言
之前不知道是因為騰訊云出了 bug 還是咋的,已經(jīng)畢業(yè)的學生證還是可以在騰訊云上購買學生套餐目木,于是花了 300 不到買了 3 年的服務器,買完之后就擱置在一盤沒有怎么用了烤芦。
最近有想法弄點自己的小東西愕提,需要掛載到服務器上,于是就拿出了塵封已久的服務器华匾,搭建下環(huán)境了映琳,也好了解下怎么簡單的搭建服務器。
搭建
nginx 安裝
通過阿里云控制臺登錄控制臺蜘拉,或者通過本地ssh
登錄服務器:
ssh root@server # server 是你服務器的ip地址
之后會讓輸入密碼萨西,輸入之后就登錄成功了。
然后我們安裝nginx
旭旭,通過yum
命令安裝:
yum install -y nginx
等待一會后距贷,nginx 就安裝上了祠锣,然后我們啟動nginx
:
service nginx start
::: tip 其他命令
service nginx restart
# 重啟nginx
服務
service nginx stop
# 停止nginx
服務
:::
然后打開瀏覽器,輸入服務器的 ip 地址咽扇,如果出現(xiàn)以下界面就表示成功了:
是不是很簡單?
配置 https
之所以想配置https
是因為以下幾點:
- 安全
- 利于 SEO
- 防劫持
因為窮宁舰,沒錢購買 ssl 安全證書。。矢否。只好用免費的了。脑溢。僵朗。這里使用的是certbot-auto
免費生成密鑰。
首先安裝certbot-auto
:
wget https://dl.eff.org/certbot-auto
安裝結束后屑彻,我們修改下certbot-auto
所在目錄的權限并暫時關閉nginx
服務:
chown a+x ./certbot-auto
service nginx stop
然后我們使用certbot-auto
生成證書验庙,生成證書有兩種模式:
- standalone
- webroot
區(qū)別
使用standalone
模式生成的證書,如果到期后社牲,更新證書需要重啟服務粪薛,而webroot
模式不需要,因為webroot
模式會在項目目錄下生成一個隱藏的文件搏恤,并且通過這個隱藏文件來驗證违寿,所以到期更新證書的時候不需要重啟服務。
使用 standalone 生成證書
./certbot-auto certonly --standalone --email 郵箱地址 -d 域名1
提示
如果多個域名熟空,直接后面接連跟著 -d 域名地址藤巢,比如:./certbot-auto certonly --standalone -d 域名1 -d 域名2
使用 webroot 生成證書
./certbot-auto certonly --webroot --email 郵箱地址 -w 項目地址 -d 域名1 -d 域名2
生成后的證書會存在/etc/letsencrypt/live/你的域名/
這個目錄中。
最后一步就是配置nginx
:
vim /etc/nginx/nginx.conf # 打開nginx的配置文件
在server
中配置ssl
:
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name www.yourdomain.com yourdomain.com; # 域名綁定
root /var/project/; # 項目目錄
# 證書配置
ssl on;
ssl_certificate "/etc/letsencrypt/live/yourdomain/fullchain.pem";
ssl_certificate_key "/etc/letsencrypt/live/yourdomain/privkey.pem";
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
}
配置好后使用service nginx start
重啟nginx
就可以了息罗。
這樣訪問你自己的域名就可以了掂咒,比如我自己的https://weixiaomu.com。
效果圖如下:
但是迈喉,如果我想普通訪問域名時自動跳到https下該怎么設置绍刮?
不難,我們在nginx
配置文件中挨摸,新建立一個server
录淡,當訪問http
的時候,重定向到https
即可:
server {
listen 80;
server_name yourdomain.com;
return 301 https://$server_name$request_uri;
}
然后重啟下nginx
就可以了油坝。