---
title: "搭建Nginx+Java环境"
author: "zc_zhou_zhouchao"
date: "2015-09-08T08:58:39Z"
tags: []
categories: ["行业应用"]
slug: "nginx-java"
draft: false
lastmod: "2015-09-08T08:58:39Z"
id: 2241537
url: "https://java-ahz.iteye.com/blog/2241537"
---

一、简介：

Tomcat在高并发环境下处理动态请求时性能很低，而在处理静态页面更加脆弱。虽然Tomcat的最新版本支持epoll，但是通过Nginx来处理静态页面要比通过Tomcat处理在性能方面好很多。

二、下载安装：

下载nginx

[http://nginx.org/en/download.html](http://nginx.org/en/download.html)

下载解压后放到C:\\nginx-1.0.4（官网这样要求的，不知道放其它盘有没有问题）

启动nginx.exe，然后在浏览器输入127.0.0.1即可

配置自己的项目测试

第二环节我们使用了默认的nginx.conf 。Nginx的配置文件都存于目录conf文件下，其中nginx.conf是它的主配置文件。

以下为我加上注释并配置的新的虚拟server

**\[plain]** [view plain](http://blog.csdn.net/kai_wei_zhang/article/details/8655842 "view plain")[copy](http://blog.csdn.net/kai_wei_zhang/article/details/8655842 "copy")

001. #运行用户
002. #user  nobody;
003. #开启进程数 &lt;=CPU数
004. worker\_processes  1;
005. #错误日志保存位置
006. #error\_log  logs/error.log;
007. #error\_log  logs/error.log  notice;
008. #error\_log  logs/error.log  info;
009. #进程号保存文件
010. #pid        logs/nginx.pid;
011. #等待事件
012. events {
013. #Linux下打开提高性能
014. #use epoll;
015. #每个进程最大连接数（最大连接=连接数x进程数）
016. worker\_connections  1024;
017. }
018. http {
019. #文件扩展名与文件类型映射表
020. include       mime.types;
021. #默认文件类型
022. default\_type  application/octet-stream;
023. #日志文件输出格式 这个位置相于全局设置
024. #log\_format  main  '$remote\_addr - $remote\_user \[$time\_local] "$request" '
025. #                  '$status $body\_bytes\_sent "$http\_referer" '
026. #                  '"$http\_user\_agent" "$http\_x\_forwarded\_for"';
027. #请求日志保存位置
028. #access\_log  logs/access.log  main;
029. #设定请求缓冲
030. client\_header\_buffer\_size 1k;
031. large\_client\_header\_buffers 4 4k;
032. #打开发送文件
033. sendfile        on;
034. #tcp\_nopush     on;
035. #keepalive\_timeout  0;
036. keepalive\_timeout  65;
037. #客户端上传文件大小控制
038. client\_max\_body\_size 8m;
039. #打开gzip压缩
040. #gzip  on;
041. #设定负载均衡的服务器列表
042. #upstream mysvr {
043. #    #weigth参数表示权值，权值越高被分配到的几率越大
044. #    #本机上的Squid开启3128端口
045. #    #server 192.168.8.1:3128 weight=5;
046. #    #server 192.168.8.2:80 weight=1;
047. #    #server 192.168.8.3:80 weight=6;
048. #}
049. #第一个虚拟主机
050. server {
051. #监听IP端口
052. listen       80;
053. #主机名
054. server\_name  localhost;
055. #root
056. #设置字符集
057. #charset koi8-r;
058. #本虚拟server的访问日志 相当于局部变量
059. #access\_log  logs/host.access.log  main;
060. #日志文件输出格式
061. #log\_format  main  '$remote\_addr - $remote\_user \[$time\_local] "$request" '
062. #                  '$status $body\_bytes\_sent "$http\_referer" '
063. #                  '"$http\_user\_agent" "$http\_x\_forwarded\_for"';
064. location / {
065. root   html;
066. index  index.html index.htm;
067. }
068. #静态文件缓存时间设置
069. #location ~ .\*\\.(gif|jpg|jpeg|png|bmp|swf)${
070. #    expires 30d;
071. #}
072. #静态文件缓存时间设置
073. #location ~ .\*\\.(js|css)?${
074. #    expires 1h;
075. #}
076. #对本server"/"启用负载均衡
077. #location / {
078. #    proxy\_pass http://mysvr;
079. #    proxy\_redirect off;
080. #    proxy\_set\_header Host $host;
081. #    proxy\_set\_header X-Real-IP $remote\_addr;
082. #    proxy\_set\_header X-Forwarded-For $proxy\_add\_x\_forwarded\_for;
083. #    client\_max\_body\_size 10m;
084. #    client\_body\_buffer\_size 128k;
085. #    proxy\_connect\_timeout 90;
086. #    proxy\_send\_timeout 90;
087. #    proxy\_read\_timeout 90;
088. #    proxy\_buffer\_size 4k;
089. #    proxy\_buffers 4 32k;
090. #    proxy\_busy\_buffers\_size 64k;
091. #    proxy\_temp\_file\_write\_size 64k;
092. #}
093. #设定查看Nginx状态的地址
094. #location /NginxStatus {
095. #    stub\_status on;
096. #    access\_log on;
097. #    auth\_basic “NginxStatus”;
098. #    auth\_basic\_user\_file conf/htpasswd;
099. #}
100. #error\_page  404              /404.html;
101. # redirect server error pages to the static page /50x.html
102. \#
103. error\_page   500 502 503 504  /50x.html;
104. location = /50x.html {
105. root   html;
106. }
107. # proxy the PHP scripts to Apache listening on 127.0.0.1:80
108. \#
109. #location ~ \\.php$ {
110. #    proxy\_pass   http://127.0.0.1;
111. #}
112. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
113. \#
114. #location ~ \\.php$ {
115. #    root           html;
116. #    fastcgi\_pass   127.0.0.1:9000;
117. #    fastcgi\_index  index.php;
118. #    fastcgi\_param  SCRIPT\_FILENAME  /scripts$fastcgi\_script\_name;
119. #    include        fastcgi\_params;
120. #}
121. # deny access to .htaccess files, if Apache's document root
122. # concurs with nginx's one
123. \#
124. #location ~ /\\.ht {
125. #    deny  all;
126. #}
127. }
128. # another virtual host using mix of IP-, name-, and port-based configuration
129. server {
130. #多监听
131. listen       localhost:8666;
132. #主机名
133. server\_name  LIULJ2576;
134. #WEB文件路径
135. root         E:/Portal;
136. #默认首页
137. index        HomePage.html;
138. #location / {
139. #    #这里相当于局部变量
140. #    root   E:/Portal;
141. #    index  HomePage.html;
142. #}
143. }
144. # HTTPS server HTTPS SSL加密服务器
145. \#
146. #server {
147. #    listen       443;
148. #    server\_name  localhost;
149. #    ssl                  on;
150. #    ssl\_certificate      cert.pem;
151. #    ssl\_certificate\_key  cert.key;
152. #    ssl\_session\_timeout  5m;
153. #    ssl\_protocols  SSLv2 SSLv3 TLSv1;
154. #    ssl\_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
155. #    ssl\_prefer\_server\_ciphers   on;
156. #    location / {
157. #        root   html;
158. #        index  index.html index.htm;
159. #    }
160. #}
161. }

#号为注释内容，我们在cmd下运行nginx

启动成功，出错的话，可以查询日志（日志路径是配置文件指定的，你可以修改存到其它位置）

访问一下第二个server 配置的localhost:8666地址，结果出现

 

三、Nginx可以通过以下两种方式来实现与Tomcat的耦合：

将静态页面请求交给Nginx，动态请求交给后端Tomcat处理。

将所有请求都交给后端的Tomcat服务器处理，同时利用Nginx自身的负载均衡功能进行多台Tomcat服务器的负载均衡。

下面通过两个配置实例分别讲述这两种实现

一、动态页面和静态页面分离的实例

这里假定Tomcat服务器的IP地址为192.168.12.130，同时Tomcat服务器开放的服务器端口为8080。Nginx相关配置代码如下：

**\[plain]** [view plain](http://blog.csdn.net/kai_wei_zhang/article/details/8655842 "view plain")[copy](http://blog.csdn.net/kai_wei_zhang/article/details/8655842 "copy")

01. server {
02. listen 80;
03. server\_name www.ixdba.net;
04. root /web/www/html;
05. location /img/ {
06. alias /web/www/html/img/;
07. }
08. location ~ (\\.jsp)|(\\.do)$ {
09. proxy\_pass http://192.168.12.130:8080;
10. proxy\_redirect off;
11. proxy\_set\_header Host $host;
12. proxy\_set\_header X-Real-IP $remote\_addr;
13. proxy\_set\_header X-Forwarded-For $proxy\_add\_x\_forwarded\_for;
14. client\_max\_body\_size 10m;
15. client\_body\_buffer\_size 128k;
16. proxy\_connect\_timeout 90;
17. proxy\_send\_timeout 90;
18. proxy\_read\_timeout 90;
19. proxy\_buffer\_size 4k;
20. proxy\_buffers 4 32k;
21. proxy\_busy\_buffers\_size 64k;
22. proxy\_temp\_file\_write\_size 64k;
23. }
24. }

 

在这个实例中，首先定义了一个虚拟主机[www.ixdba.net](http://www.ixdba.net/)，然后通过location指令将/web/www/html/img/目录下的静态文件交给Nginx来完成。最后一个location指令将所有以.jsp、.do结尾的文件都交给Tomcat服务器的8080端口来处理，即[http://192.168.12.130:8080](http://192.168.12.130:8080/)。

需要特别注意的是，在location指令中使用正则表达式后，proxy\_pass后面的代理路径不能含有地址链接，也就是不能写成[http://192.168.12.130:8080/](http://192.168.12.130:8080/)，或者类似[http://192.168.12.130:8080/jsp](http://192.168.12.130:8080/jsp)的形式。在location指令不使用正则表达式时，没有此限制。

2、多个tomcat负载均衡的实例

这里假定有3台Tomcat服务器，分别开放不同的端口，地址如下：

**\[plain]** [view plain](http://blog.csdn.net/kai_wei_zhang/article/details/8655842 "view plain")[copy](http://blog.csdn.net/kai_wei_zhang/article/details/8655842 "copy")

1. 192.168.12.131:8000
2. 192.168.12.132:8080
3. 192.168.12.133:8090

Nginx的相关配置代码如下：

**\[plain]** [view plain](http://blog.csdn.net/kai_wei_zhang/article/details/8655842 "view plain")[copy](http://blog.csdn.net/kai_wei_zhang/article/details/8655842 "copy")

01. upstream mytomcats {
02. server 192.168.12.131:8000;
03. server 192.168.12.132:8080;
04. server 192.168.12.133:8090;
05. }
06. server {
07. listen 80;
08. server\_name www.ixdba.net;
09. location ~* \\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
10. root /web/www/html/;
11. }
12. location / {
13. proxy\_pass http://mytomcats;
14. proxy\_redirect off;
15. proxy\_set\_header Host $host;
16. proxy\_set\_header X-Real-IP $remote\_addr;
17. proxy\_set\_header X-Forwarded-For $proxy\_add\_x\_forwarded\_for;
18. client\_max\_body\_size 10m;
19. client\_body\_buffer\_size 128k;
20. proxy\_connect\_timeout 90;
21. proxy\_send\_timeout 90;
22. proxy\_read\_timeout 90;
23. proxy\_buffer\_size 4k;
24. proxy\_buffers 4 32k;
25. proxy\_busy\_buffers\_size 64k;
26. proxy\_temp\_file\_write\_size 64k;
27. }
28. }