本文共 1740 字,大约阅读时间需要 5 分钟。
安装Nginx需要先安装以下三个依赖包:
yum install openssl
yum install zlib
yum install pcre
安装Nginx时需要先加载Nginx的YUM仓库,可以通过以下命令:
rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
接下来安装Nginx:
yum install nginx
启动Nginx服务:
service nginx start
安装完成后,访问localhost即可看到Nginx欢迎界面。如果没有访问成功,可能是防火墙设置的问题。可以通过以下命令查看已开放的端口:
firewall-cmd --list-ports
如果默认80端口未开放,可以将其加入防火墙白名单:
firewall-cmd --permanent --zone=public --add-port=80/tcp
然后重启防火墙:
firewall-cmd --reload
Nginx的配置文件位于/etc/nginx/conf.d/default/nginx.conf。Nginx的配置文件结构从外到内依次是http、server、location等,内层块会继承外层块的缺省值。
server块用于定义虚拟主机,接收请求并转发到后端服务器。基本配置示例:
server { listen 80; server_name localhost; root html; index index.html index.htm;} 可以通过多个server块分别配置不同的域名和服务:
server { listen 80; server_name passport.bigertech.com; root /data/www/passport; index index.html index.htm;}server { listen 80; server_name wan.bigertech.com; root /data/www/wan; index index.html index.htm;} 主配置文件中可以通过include指令加载多个server配置文件:
include vhosts/*.conf;
location块用于匹配URL路径,并对请求进行处理或转发。location匹配规则包括普通字符、正则表达式(~或~*)和区分大小写的匹配。
静态文件映射主要通过root和alias指令实现:
root:指定完整目录路径,需包含与location路径相同名称的目录。alias:指定准确路径,需以/结尾。例如:
location /c/ { alias /a/;}location /c/ { root /a/;} location块也可以用于反向代理,例如将所有请求转发到指定服务器:
location / { proxy_pass 172.16.1.1:8001;} 负载均衡可以通过upstream块实现:
upstream myserver { ip_hash; server 172.16.1.1:8001; server 172.16.1.2:8002; server 172.16.1.3; server 172.16.1.4;}location / { proxy_pass http://myserver;} 配置完成后,可以通过以下命令验证配置是否正确:
nginx -t
或者指定配置文件:
nginx -tc /path/to/nginx.conf
转载地址:http://ohrt.baihongyu.com/