nginx+tomcat使用

1.官网下载地址:http://nginx.org/en/download.html可以到这里去下。
2.找到下载的对应文档地址使用start nginx启动nginx,你会发现有个窗口一闪而过,不用担心已经启动了你可以在任务进程中看到nginx.exe的执行的映像。
3.localhost访问是不是出现nginx的标识“Welcome to nginx!”如果出现就证明你成功了
4.nginx启动成功,现在就涉及到nginx的一个重要配置文件nginx.conf了。
我们可看到这么一段代码
server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

listen:表示当前的代理服务器监听的端口,默认的是监听80端口。注意,如果我们配置了多个server,这个listen要配置不一样,不然就不能确定转到哪里去了。
server_name:表示监听到之后需要转到哪里去,这时我们直接转到本地,这时是直接到nginx文件夹内。
location:表示匹配的路径,这时配置了/表示所有请求都被匹配到这里
root:里面配置了root这时表示当匹配这个请求的路径时,将会在这个文件夹内寻找相应的文件,这里对我们之后的静态文件伺服很有用。
index:当没有指定主页时,默认会选择这个指定的文件,它可以有多个,并按顺序来加载,如果第一个不存在,则找第二个,依此类推。
下面的error_page是代表错误的页面,这里我们暂时不用,先不管它。
我们修改

server_name localhost:8080;  
  
location / {  
    proxy_pass 你的项目的首地址  
}  

nginx在修改后不需要重启运行 nginx -s reload  就可以了
如果想知道是不是有效的 nginx -t测试一下就好
已经成功了,实际上我们的需要并不仅仅是那样的
上面我们直接试了一个小例子,让nginx进行转发,即所 谓的反向代理。但实际上我们的需求不会是这样的,我们需要分文件类型来进行过滤,比如jsp直接给tomcat处理,因为nginx并不是servlet 容器,没办法处理JSP,而html,js,css这些不需要处理的,直接给nginx进行缓存。
下面我们来进行一下配置,让JSP页面直接给tomcat,而html,png等一些图片和JS等直接给nginx进行缓存。
这时最主要用的还是location这个元素,并且涉及到一部分正则,但不难:
location ~ \.jsp$ {  
        proxy_pass http://localhost:8080;  
}  
          
location ~ \.(html|js|css|png|gif)$ {  
    root D:/software/developerTools/server/apache-tomcat-7.0.8/webapps/ROOT;  
}  

一般情况下,如果我们需要用nginx来进行静态文件私服,一般都会把所有静态文件,html,htm,js,css等都放在同一个文件夹下,这样就不会有tomcat这样的情况了,因为tomcat下的是属于不同的项目,这个我们就没办法了。

如果我们想在一台服务器挂了的时候,自动去找另外一台,这怎么办?这实际上nginx都考虑到了。之前用的proxy_pass就有大用途了。
我们把之前的第一个例子,即全部都代理的修改一下:
我们在server外添加了一个upstream,而直接在proxy_pass里面直接用http://+upstream的名称来使用
在upstream中的local_tomcat中配置多一个server。
如果session在登录时候老是会跳动就在多服务配置哪里加 ip_hash;

猜你喜欢

转载自janle.iteye.com/blog/2250981