search
HomeBackend DevelopmentPHP TutorialUsing Nginx to implement virtual host under Centos7.2

1. Preface

First you need to make sure that Nginx has been installed correctly in your Linux system. Of course, if Nginx is not installed, please refer to

System environment:
Linux environment : centos-7.2
Nginx environment: nginx-1.9.9

2. About Nginx
Nginx is a high-performance http server/reverse proxy server and email (IMAP/POP3) proxy server. Developed by Russian programmer Igor Sysoev, official testing of nginx can support 50,000 concurrent connections, consumes very little resources such as CPU and memory, and runs very stably. Open source and free.


3. What can you do with Nginx?
1. http server: Nginx is an http service that can provide http services independently. Can be used as a static web server.
2. Virtual host: multiple websites can be virtualized on one server. For example, a virtual host used by a personal website.
3. Reverse proxy/load balancing: When the number of visits to the website reaches a certain level and a single server cannot satisfy user requests, multiple server clusters are needed and nginx can be used as a reverse proxy. And multiple servers can share the load evenly, and there will be no downtime due to a high load on a certain server and a certain server will not be idle.


4. Use Nginx to implement virtual host
Here we need to know why we need to create a virtual host. In the actual production environment, our business is accessed through the public network.
When I build a cloud server, one cloud server corresponds to a public IP, so public IP is a very scarce resource for ordinary companies.
For some large companies, such as BAT, it may not matter. .
So using Nginx to implement a virtual host here can run multiple websites on the same service without interfering with each other.


The same server may have an IP, and the website needs to use port 80, but the domain name of the website is different.
There are three ways to distinguish different websites:

1, http service
2, virtual machine implementation
1) IP-based virtual machine
2) Port-based Virtual machine
3) Domain name-based virtual machine
3, reverse proxy, load balancing

5. IP-differentiated virtual host

Bind multiple ones on one server IP address.
Method 1:
Use standard network configuration tools (such as ifconfig and route commands) to add IP aliases,

Enter the command "ifconfig" to view the current ip configuration, as shown below:


Bind another IP to the ens33 network card: 192.168.78.142, and name the network card ens33:1

/sbin/ifconfig ens33:1 192.168.78.142 broadcast 192.168.78.255 netmask 255.255.255.0 up
/sbin/route add -host 192.168.78.142 dev ens33:1

After the virtual network card is created, as shown below:



Method 2:
1. Change /etc/sysconfig/network-scripts/ifcfg- Copy the ens33 file,

Enter the directory, enter the command "cp ifcfg-ens33 ifcfg-ens33:1 -r" and name it ifcfg-ens33:1, as shown below:


2. Modify the configuration file, enter the command "vi ifcfg-ens33:1", modify the following content,

NAME=ens33:1
DEVICE=ens33:1
IPADDR=192.168.78.142

No need to modify other items, after the modification is completed , as shown below:


After the creation is completed, test whether the new IP is successfully bound, enter the command "ping 192.168.78.142" in the DOS window, as shown below :


#Note: The IP bound using method one will be automatically unbound after the system restarts and needs to be re-bound. Method two is permanent. , this is a practical conclusion.
3. Restart the system,
Enter the command "reboot", restart the system and then enter the command "ifconfig", you can see that a new network card is created normally,
as shown below:

6. nginx implements virtual machine

1) Configure nginx virtual host based on IP address
Prepare two HTMLs that identify nginx for easy differentiation during testing : Go to the /usr/local/nginx directory and copy the html into two copies respectively.

Modify the content of index.html below. It’s simpler so I won’t write it here. If you don’t know, please leave a message. Or send a private message as shown below:


##Modify the nginx configuration file and enter the command "vi conf/nginx.config"


Convenience Reader's copy, I have deleted the unnecessary ones here, the content is as follows:

    server {
        listen       80;
        server_name  192.168.78.141;




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


    }


    server {
        listen       80;
        server_name  192.168.78.142;




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


    }
As shown below:


测试nginx 虚拟主机是否可以正常访问,

测试 192.168.78.141 虚拟主机,如下图:




测试 192.168.78.142 虚拟主机,如下图:




2)、配置 nginx 基于端口的虚拟主机
还是老规矩,准备两个标识 nginx 的 HTML,用于在测试时好区别:进入到 /usr/local/nginx 目录下,将 html 分别复制两份,

在修改下面 index.html 的内容,这儿较简单就不在写了,如果不知道请留言或私信,如下图:


修改 nginx 的配置文件,输入命令 “ vi conf/nginx.config ”

方便读者的复制,内容如下:

server {
        listen       81;
        server_name  192.168.78.141;




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


    }


    server {
        listen       82;
        server_name  192.168.78.141;




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


    }

如下图所示:


重启Nginx 后,测试nginx 虚拟主机是否可以正常访问,

测试 81端口的 虚拟主机,如下图:


测试 82端口的 虚拟主机,如下图:





3)、基于域名的虚拟主机
基于域名的虚拟主机是最有用的虚拟主机配置方式。
即一个域名只能绑定一个ip地址,一个ip地址可以被多个域名绑定。


实现基于域名的虚拟主机,在这儿还需要修改 Linux 的 HostName,当然还可以通过 这个工具进行修改 ,对于互联网开发的人来说,经常变更 host 必不可免。每次我们都一遍一遍的去修改hosts文件真是很累,如果能更快速的修改成不同hosts,这儿为大家推荐一个好用的软件 SwitchHosts ,轻松一键切换。

以管理员身份打开,然后就可以设置域名和ip的映射关系,新增一个本地解决方案,键入如下内容,

192.168.78.141 www.12345.com
192.168.78.141 register.12345.com
192.168.78.141 login.12345.com

如下图:




注:修改window的hosts文件:(C:\Windows\System32\drivers\etc)


基于 Nginx 域名的虚拟主机配置,修改内容如下图:


    server {
        listen       80;
        server_name  www.12345.com;




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


    }




    server {
        listen       80;
        server_name  register.12345.com;




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


    }


    server {
        listen       80;
        server_name  login.12345.com;




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


    }

如下图所示:



修改配置文件后,需要 nginx 重新加载配置文件。

测试 www.12345.com,如下图:


测试 register.12345.com,如下图:


测试 login.12345.com,如下图:


相关推荐:

win10 apache配置虚拟主机后localhost无法使用

详解Linux虚拟主机相关问题

关于php之Apache配置虚拟主机

The above is the detailed content of Using Nginx to implement virtual host under Centos7.2. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools