首页 > 技术文章 > Nginx安装配置

linn 2014-09-17 14:15 原文

安装

1、安装pcre支持正则表达式

wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.35.tar.gz
tar zxvf pcre-7.7.tar.gz
cd pcre-7.7
./configure
make
make install

 

2、安装gzip

yum install -y zlib-devel

 

3、安装openssl

yum install openssl-devel

$ yum -y install gcc gcc-c++ autoconf automake
 
$ yum -y install zlib zlib-devel openssl openssl-devel pcre-devel

pcre: 用来作地址重写的功能。

zlib:nginx 的gzip模块,传输数据打包,省流量(但消耗资源)。

openssl:提供ssl加密协议。

 

4、安装nginx

wge http://nginx.org/download/nginx-1.6.1.tar.gz
tar zxvf nginx-0.6.31.tar.gz
cd nginx-0.6.31
./configure --with-http_ssl_module --with-http_stub_status_module
make
make install

 

默认情况下,Nginx 会被安装在 /usr/local/nginx。

目录下有四个子目录分别是:conf、html、logs、sbin 。其中 Nginx 的配置文件存放于 conf/nginx.conf,Nginx 只有一个程序文件位于 sbin 目录下的 nginx 文件。确保系统的 80 端口没被其他程序占用,运行 sbin/nginx 命令来启动 Nginx,打开浏览器访问此机器的 IP,如果浏览器出现 Welcome to nginx! 则表示 Nginx 已经安装并运行成功。

常见问题

如果发现浏览器没法访问,请检查端口是否打开:

netstat –apn | grep 80

如果端口打开了,请测试是否防火墙问题:

telnet  ip地址 80

如果是防火墙问题,可以先关闭防火墙:

chkconfig iptables off 

service iptables stop 

 

配置HTTP代理

server {
listen 80;
server_name localhost;
charset utf-8;
#access_log logs/host.access.log main;
location / {
proxy_pass http://10.20.126.81:8001;
root html;
index index.html index.htm;
}
}

 

配置HTTPS代理

特别提示:这里所指的反向代理https是指nginx为ssl服务器,nginx与后端服务器的通信还是http

1、nginx要实现ssl,在编译时要添加--with-http_ssl_module。 

./configure --with-http_ssl_module

 

2、创建放置证书的目录 

#cd /usr/local/nginx/conf
#mkdir ssl
#cd ssl

 

3、生成key

生成一个私有key
# openssl genrsa -des3 -out app.data.key 2048
提示输入密码
生成CSR(Certificate Signing Request)文件:
# openssl req -new -key app.data.key -out app.data.csr
填写证书内容,组织机构、域名等,Common Name填写域名
# cp app.data.key app.data.key.bak
转密码,避免每次启动nginx都需要手工输入密码
# openssl rsa -in app.data.key.bak -out app.data.key
生成证书
# openssl x509 -req -days 1000 -in app.data.csr -signkey app.data.key -out app.data.crt

 

4、配置nginx.conf

核心内容:

server {
listen 443 ssl;
server_name localhost;

charset utf-8;

#access_log logs/host.access.log main;

### SSL cert files ###
ssl_certificate ssl/app.data.crt;
ssl_certificate_key ssl/app.data.key;

location / {
proxy_pass http://10.20.126.81:8001;

 

 
但是有些程序只会给你往端口上转发,不会自动修正http为https,这样的程序还不少,例如phpmyadmin:

遇到这样的程序我们需要修改Nginx.conf配置文件,在443的server的fastcgi字段中添加一个语句:

fastcgi_param HTTPS on; #attention!#
例如

location ~ .*\.(php|php5)?$
            {
                try_files $uri =404;
                fastcgi_pass  unix:/tmp/php-cgi.sock;
                fastcgi_index index.php;
                fastcgi_param HTTPS on; #attention!#
                include fcgi.conf;
            }
这样就可以了。

 

 
 
 

推荐阅读