centos6.x yum默认没有nginx的软件包
安装方式:
到nginx下载页面http://nginx.org/en/linux_packages.html#stable,复制CENTOS 6的nginx软件源安装包
运行命令:wget http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
安装rpm包 yum install nginx-release-centos-6-0.el6.ngx.noarch.rpm -y , 此步实际只是加入了nginx的软件包源
执行 yum install nginx -y 就可以安装好nginx了。
nginx默认安装为Linux的服务 ,所以可以使用service nginx start, stop, restart, try-restart, reload, force-reload, status来操作nginx。
nginx的配置文件默认读取/etc/nginx/nginx.conf文件。
当然也可以修改使用的conf路径,使用命令:我们都知道如果在域名管理的控制面板设置域名对应ip只能设置到ip,不能详细设置到端口。如果一台服务器部署了多个web应用,使用的不同端口启动的,那么就可以Nginx做映射。
比如我有一个域名 www.525.life。
域名还可以分出2级域名: admin.525.life。
我在域名控制面板把这两个域名都指向我的服务器公网ip 123.123.123.123。
这时候发现www.525.life和admin.525.life域名访问都只是对应到了 使用端口80的Web程序(默认的)。
如果我们要访问81端口的应用程序只能使用:
www.525.life:81或者
admin.525.life:81。
但是这样很不方便。我们要把端口去掉也能访问就需要使用Nginx做映射。
我们期望www.525.life访问8880端口,admin.525.life访问8881端口。那么可以设置如下:
server
{
listen 80;
server_name www.525.life;
location / {
#....
proxy_pass http://localhost:8880;
}
##### other directive
}
server
{
listen 80;
server_name admin.525.life;
location / {
#....
proxy_pass http://localhost:8881;
}
##### other directive
}
这样设置就可以了。把8880和8881都映射到80端口的监听。
使用重载命令使nginx生效:
sudo nginx -s reload
使用命令重启nginx生效:
/etc/init.d/nginx restart
这样就能使用www.525.life访问8880端口,admin.525.life访问8881端口。
我们在上面的例子中使用的是一个文件多个域名的写法,也就是只使用一个conf,在里面不断的增加server。这种方式很直观,但是域名多了不好管理。
Nginx支持引入的用法,也就是我们可以在其他地方先新建好conf文件,conf文件中记录server的信息如下:
admin.conf中的内容是:
server
{
listen 80;
server_name admin.525.life;
location / {
#....
proxy_pass http://localhost:8881;
}
##### other directive
}
www.conf中的内容是:
server
{
listen 80;
server_name www.525.life;
location / {
#....
proxy_pass http://localhost:8880;
}
##### other directive
}
admin.conf和www.conf都放在/data/nginx/conf/vhost目录下。
然后在nginx.conf中使用引入命令:
include /data/nginx/conf/vhost/*.conf;
即可。
需要注意的是这句命令应该放在
http{
}
的花括号内。
因为include的命令引入相当于被引入的所有代码写在nginx.conf中一样。
我们留意到生活中很多时候不带www也能访问到某个网站,这也能通过Nginx实现。跟上面的配置一样,再增加一个server如下:
server
{
listen 80;
server_name 525.life;
location / {
#....
proxy_pass http://localhost:8880;
}
##### other directive
}
或者进行301跳转
server
{
listen 80;
server_name 525.life;
rewrite ^/(.*) http://www.525.life/$1 permanent;
}