分类
代码

Nginx 简单使用

安装

sudo apt install nginx-full

如果之前安装过 apache2, 建议先卸载掉……

如果没有意外的话,打开 http://localhost/ 就可以看到默认欢迎页了。

配置

安装后配置文件都在 /etc/nginx 下。打开 nginx.conf 可以看到,会把 conf.d 文件夹下所有的 *.conf 文件都包含进来。因此我们可以把自定义配置文件放在 conf.d 目录下。

这里假设我们需要配置一个域名:youthlin.local, 于是我在 conf.d 目录下新建一个文件 youthlin.local.conf, 文件名任意,conf 结尾就行。然后键入内容:

#upstream 表示实际的地址
upstream youthlin_local{
	server 127.0.0.1:8080;
	server 127.0.0.1:8081;
}

server {
	listen 80;
	listen [::]:80;
    #域名
	server_name youthlin.local;

	location / {
	    #真实IP,Java里就可以使用【request.getHeader("X-Real-IP")】获取IP
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header Host $host;
		#上游真实地址
		proxy_pass http://youthlin_local;
		try_files $uri $uri/ =404;
	}
}

测试

打开 IDEA,写个测试页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page trimDirectiveWhitespaces="true" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
Index<br>
<%=application%><br>
<%=request.getHeader("X-Real-IP")%>
</body>
</html>

用 Debug 起一个Tomcat,然后用 Maven 插件 tomcat7 起一个实例(mvn tomcat7:run):

 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                    <port>8081</port>
                    <server>tomcat7</server>
                    <finalName>ROOT</finalName>
                    <uriEncoding>UTF-8</uriEncoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

现在可以通过127.0.0.1:8080 和 127.0.0.1:8081 访问两个实例了。
配置 hosts:127.0.0.1 youthlin.local 然后打开 youthlin.local 就成功了~


“Nginx 简单使用”上的5条回复

[/坏笑] 貌似配置文件非.conf结尾也行
PS.
烦请老哥帮忙把友链改回“秋空(qiukong.com)”
图库转交了我好友管理,链接保持同步~
感谢!!

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

[/鼓掌] [/难过] [/调皮] [/白眼] [/疑问] [/流泪] [/流汗] [/撇嘴] [/抠鼻] [/惊讶] [/微笑] [/得意] [/大兵] [/坏笑] [/呲牙] [/吓到] [/可爱] [/发怒] [/发呆] [/偷笑] [/亲亲]