在CentOS Stream 8上实现Nginx和Tomcat共存的步骤如下:

../

我尝试在CentOS Stream 8上安装了Nginx 1.14。

由于Apache httpd在80端口进行监听,所以希望Nginx监听7080端口。选择7080端口是根据本地可用状态随意确定的。希望通过httpd的VirtualHost,仅当请求特定路径(/php)时才将其转发到Nginx。目前,httpd与Tomcat集成在一起,用于通过https进行访问,因此希望能够与Tomcat共存。

在互联网络上,经常有提到的流程是:nginx(80) –> httpd(8080) –> ajp(8009) –> tomcat(8443)。然而,我不想破坏已经存在的httpd和Tomcat,所以我尝试了以下流程。

httpd(80) --> RewriteEngine(443) -->
	if (特定のルート /php のとき){
		nginx(7080)
	} else {
		ajp(8009) --> tomcat(8443)
	}

安装Nginx 1.14。

安装Nginx1.14。

$ dnf list nginx
nginx.x86_64         1:1.14.1-9.module_el8.0.0+1060+3ab382d3          @appstream
$ dnf install nginx

注册并启动HTTP服务。

$ firewall-cmd --list-all
$ firewall-cmd --add-service=http --permanent
$ firewall-cmd --reload
$ firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eth0
  sources: 
  services: cockpit dhcpv6-client http imap mysql pop3 smtp smtp-submission vnc-server
  ports: 8080/tcp 8443/tcp 8009/tcp
  protocols: 

$ systemctl start http
$ systemctl status http

当启动Nginx服务时,默认情况下会与httpd占用同一个80端口,导致出现错误。

$ systemctl start nginx
$ systemctl status nginx
$ more /var/log/nginx/error.log

修改Nginx的配置并启动服务。将监听端口从80端口改为7080端口。在根目录中指定用于存放创建的PHP文件的目录。

$ ls /etc/nginx
$ vi /etc/nginx/nginx.conf
    server {
#       listen       80 default_server;
        listen       7080 default_server;
#       listen       [::]:80 default_server;
        listen       [::]:7080 default_server;
        server_name  _;
#       root         /usr/share/nginx/html;
        root         /opt/php74/webapps;

$ nginx -t
$ vi /etc/nginx/conf.d/php-fpm.conf
upstream php-fpm {
        server unix:/run/php-fpm/www.sock;
}

$ vi /etc/php-fpm.d/www.conf
;user = apache
user = nginx
;group = apache
group = nginx

$ systemctl start php-fpm
$ systemctl enable php-fpm

$ systemctl start nginx
$ systemctl status nginx

更改httpd配置

修改 httpd.conf 并重新启动 httpd。在我的环境中,我使用 RewriteEngine 在 VirtualHost 中将 *:80 替换为 *:443。我将这些规则写入了类似于 vhost-xxx-ssl.conf 的文件中。请编辑该文件,使得当访问 /php 时跳转到 Nginx(7080),其他情况跳转到 Tomcat(8009)。Tomcat 的文档根目录设置为 /opt/tomcat9/webapps/。我将 Nginx 的根目录设置为 /opt/php74/webapps/。

<VirtualHost *:80>
ServerName kankeri.com
...
RewriteEngine on
RewriteCond %{SERVER_NAME} =kankeri.com [OR]
RewriteCond %{SERVER_NAME} =www.kankeri.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
...
</VirtualHost>
<VirtualHost kankeri.com:443>
...
SSLProxyEngine On
ProxyRequests Off
ProxyPreserveHost On
ProxyPass        /php   http://localhost:7080/
ProxyPass 		 /      ajp://localhost:8009/
ProxyPassReverse /php/  http://localhost:7080/

SSLCertificateFile /etc/letsencrypt/live/kankeri.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/kankeri.com/privkey.pem
...
</VirtualHost>

如果通过以下链接访问,分别可以使用php和jsp进行功能操作。

http://kankeri.com/php/			--> /opt/php74/webapps/
http://kankeri.com/				--> /opt/tomcat9/webapps/
../
bannerAds