使用Nginx和Apache设置自动虚拟主机

When starting new applications, a developer often needs to set up a new virtual host. This includes setting up new configuration files for Apache or new Nginx site entries. Sometimes you need to do this manually. Other times, it’s handled automatically if you just define a site-to-folder mapping. But wouldn’t it be practical if we could skip that step, too, and just have any URL ending in, for example, .local.com look for its files automatically, so all we need to do is change our etc/hosts file only once ever? Whoa!

启动新应用程序时,开发人员通常需要设置新的虚拟主机。 这包括为Apache或新的Nginx站点条目设置新的配置文件。 有时您需要手动执行此操作。 其他时候,如果您仅定义站点到文件夹的映射,则会自动处理 。 但是,如果我们也可以跳过该步骤,并且仅以.local.com结尾的任何URL作为结尾,这是不切实际的,例如, .local.com会自动查找其文件,因此,我们要做的就是更改etc/hosts文件只有一次 过的 ? 哇!

Mind blown

In this tutorial, we’ll set up Nginx and Apache to automatically look inside certain folders when it detects a given URL format. For example, the URL mynewsite.local.com will automatically look inside the DOC_ROOT/nynewsite/public folder for the index.php file. You will then be able to define other patterns suitable for generic scripts, standard MVC apps (public/index.php) and Symfony/Silex based apps (web/app.php) – all depending on the URL format (e.g. mynewsite.sf2local.com could look inside web/ for app.php, as is typical of those frameworks).

在本教程中,我们将设置Nginx和Apache在检测到给定的URL格式时自动在某些文件夹中查找。 例如,URL mynewsite.local.com将自动在DOC_ROOT/nynewsite/public文件夹内查找index.php文件。 然后,您将能够定义适用于通用脚本,标准MVC应用程序( public/index.php )和基于Symfony / Silex的应用程序( web/app.php )的其他模式-所有这些都取决于URL格式(例如mynewsite.sf2local.com可以在web/查找app.php ,这是这些框架的典型特征)。

This tutorial will be Unix-centric, but is Windows-friendly if you use our Homestead Improved box.

本教程将以Unix为中心,但是如果您使用“ 改进Homestead”框,则对Windows友好。

Before we begin, make sure you have something.local.com in your /etc/hosts file, so that we can test this URL as we go along. If desired, modify it to your liking. I’ll be focusing on the local.com suffix for triggering Vhost lookups inside the something folder in our document root, but this can be literally anything that’s valid in a URL charset.

在开始之前,请确保您在/etc/hosts文件中具有something.local.com ,以便我们可以逐步测试该URL。 如果需要,可以根据自己的喜好对其进行修改。 我将重点关注local.com后缀,以在文档根目录的something文件夹内触发Vhost查找,但这实际上可以是在URL字符集中有效的任何内容。

为Nginx设置 (Setting up for Nginx)

Nginx Logo

Assuming you have an Nginx setup running, either via Homestead Improved or any other means, let’s create a new entry in the folder Nginx typically uses to read site configurations from: sites-available. In a standard installation, Nginx will include everything from the folder sites-enabled in its configuration. Putting the file we’re about to write into sites-available will require us to activate it later.

假设您已经通过Homestead Improvement或任何其他方式运行了Nginx设置,让我们在Nginx通常用于从以下sites-available读取站点配置的文件夹中创建一个新条目: sites-available 。 在标准安装中,Nginx将在其配置中包括sites-enabled了文件夹的所有内容。 将我们要写入的文件放入sites-available将需要我们稍后激活它。

vim /etc/nginx/sites-available/wildcard.conf

We first define a server block and tell it to listen on port 80:

我们首先定义一个server块,并告诉它侦听端口80:

server {
	listen 80;
}

Everything else we write will be put inside the server block, below the listen statement.

我们编写的所有其他内容都将放置在listen语句下方的server块中。

server_name ~^(www\.)?(?<sname>.+?).local.com$;

This right here is the most important part. It tells Nginx “The server name will come in the form of this regular expression. Pull out the sname bit, save it for later”.

这就是这里最重要的部分。 它告诉Nginx“服务器名称将以此正则表达式的形式出现。 拔出sname位,保存以备后用。”

root /home/vagrant/Code/$sname;

This tells Nginx “The root folder of this web application is in this location”. Since it appends sname from the above regex, the path becomes dynamic, corresponding to the URL. If you’re not running a virtual machine, or have a differently set up root folder in general, feel free to change this – just make sure it ends in $sname;. If your apps typically have their front controller in the public folder, feel free to append public so the root statement looks like this:

这告诉Nginx“此Web应用程序的根文件夹位于此位置”。 由于它在上述正则表达式后附加了sname ,因此该路径变为动态的,对应于URL。 如果您不是在运行虚拟机,或者总体上设置了不同的根文件夹,请随时进行更改–确保它以$sname;结尾$sname; 。 如果您的应用通常在public文件夹中具有其前端控制器,请随时附加public因此root语句如下所示:

root /home/vagrant/Code/$sname/public;

This approach is what I’ll be using in the final version of the file.

我将在文件的最终版本中使用这种方法。

The rest of the configuration can stay the same as usual. That’s more or less it, unless you would also like to have dynamic error logs, in which case the error log entries in the file should look like this:

其余配置可以保持与通常相同。 差不多就是这样,除非您还希望拥有动态错误日志,在这种情况下,文件中的错误日志条目应如下所示:

access_log /var/log/nginx/$sname-access.log;
    error_log  /var/log/nginx/wildcard-error.log debug;

Note that we cannot have a variable in the error log, only the access log. Not sure why this was implemented like this. This does mean, unfortunately, that your wildcard error logs will be merged.

请注意,错误日志中不能包含变量,只有访问日志中可以包含变量。 不知道为什么要这样实现。 不幸的是,这确实意味着您的通配符错误日志将被合并。

What follows is the full code of the configuration file we wrote. Depending on your installation, some other things may vary (like php-fpm lines etc.) but that’s outside the scope of this tutorial.

接下来是我们编写的配置文件的完整代码。 根据您的安装,其他一些情况可能会有所不同(例如php-fpm行等),但这超出了本教程的范围。

```
server {
    listen 80;
    server_name ~^(www\.)?(?<sname>.+?).local.com$;
    root /home/vagrant/Code/$sname/public;

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log /var/log/nginx/$sname-access.log;
    error_log  /var/log/nginx/wildcard-error.log debug;

    error_page 404 /index.php;

    sendfile off;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

It’s possible that your Nginx installation is set up differently, so you might need to look around for site configuration files. It’s also possible that all your Nginx configuration is in a single file, in which case just add the above configuration to it – that might also be a file called default in your sites-available folder. Doesn’t matter where this configuration is, as long as it’s loaded – see configuration auto-include locations by peeking inside etc/nginx/nginx.conf.

Nginx安装的设置可能有所不同,因此您可能需要四处寻找站点配置文件。 您所有Nginx的配置也可能都在一个文件中,在这种情况下,只需将上面的配置添加到其中-这也可能是您sites-available文件夹中的名为default文件。 不论此配置在何处加载,只要加载就无所谓–通过在etc/nginx/nginx.conf内部查看,可以查看配置自动包含位置。

Finally, we need to enable the new configuration by creating a symlink in the sites-enabled folder:

最后,我们需要通过在sites-enabled文件夹中创建符号链接来启用新配置:

sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myapp
sudo service nginx restart

If you now visit something.local.com in your browser, the files from (in my case) vagrant/Code/something/public will be loaded.

如果您现在在浏览器中访问something.local.com ,则将从(在我的情况下) vagrant/Code/something/public中的文件加载。

设置Apache (Setting up for Apache)

Apache Logo

In this section, I’ll assume you have a running Apache instance that serves your PHP sites as usual. This could be via PuPHPet or with your friendly neighborhood *AMP stack, irrelevant – as long as it works.

在本节中,我假设您有一个正在运行的Apache实例,该实例照常为PHP网站提供服务。 只要可行,就可以通过PuPHPet或与您友好的邻域* AMP堆栈无关。

First, we need to make sure mod_vhost_alias is enabled. This is the Apache mod used to give us the functionality we need. There are two ways to do this. In more streamlined installations, the command a2enmod will be available in the terminal, and all it takes is sudo a2enmod vhost_alias. In others, again due to the curse of Linux, you’ll need to look inside the main configuration file, either /etc/apache2/apache2.conf or /etc/apache2/httpd.conf or the like. If this is your case, try and find a line containing mod_vhost_alias. If it’s not there, add the following line:

首先,我们需要确保启用了mod_vhost_alias 。 这是用于为我们提供所需功能的Apache mod。 有两种方法可以做到这一点。 在更简化的安装中,命令a2enmod将在终端中可用,而所需的只是sudo a2enmod vhost_alias 。 在其他情况下,同样由于Linux的诅咒,您需要查看主配置文件,其中是/etc/apache2/apache2.conf/etc/apache2/httpd.conf等。 如果是这种情况,请尝试查找包含mod_vhost_alias的行。 如果不存在,请添加以下行:

LoadModule vhost_alias_module modules/mod_vhost_alias.so

Note that the path at the end needs to match the location of Apache modules on your system. This also varies due to the curse of Linux, but is often in /etc/apache2/mods-available.

请注意,最后的路径需要与系统上Apache模块的位置匹配。 这也由于Linux的诅咒而有所不同,但通常在/etc/apache2/mods-available

Just like Nginx, Apache usually loads its Vhost configurations from /etc/apache2/sites-available and by extension /etc/apache2/sites-enabled. It usually also comes with a module for easy enabling and disabling of sites, like so: sudo a2ensite mysite.conf. This is, for all intents and purposes, identical to the Nginx section above on creating a symlink to enable a new configuration. It loads these alphabetically, so we’ll make a new configuration file in sites-enabled (or do it in sites-available and enable the site subsequently) called 000-default.conf.

就像Nginx一样,Apache通常从/etc/apache2/sites-available以及通过扩展/etc/apache2/sites-enabled加载其Vhost配置。 它通常还带有一个用于轻松启用和禁用站点的模块,例如: sudo a2ensite mysite.conf 。 出于所有意图和目的,这与上面有关创建符号链接以启用新配置的Nginx部分相同。 它会按字母顺序加载这些文件,因此我们将在sites-enabled创建一个新的配置文件(或在sites-available然后再启用该站点),称为000-default.conf

The first statement we put in there will be:

我们输入的第一个语句将是:

UseCanonicalName Off

This is required so that we can dynamically assign aliases to the URLs Apache receives. Then, we define the VirtualHost block:

这是必需的,以便我们可以为Apache接收的URL动态分配别名。 然后,我们定义VirtualHost块:

<VirtualHost *:80>
	ServerName vhosts.fqdn
	ServerAlias *.local.com
	VirtualDocumentRoot /var/www/%1+
</VirtualHost>

The %1 means “Take the first part of the dot-separated domain name”. For other options, and if you wish to configure it differently, see the docs.

%1意思是“使用点号分隔的域名的第一部分”。 有关其他选项,并且如果您希望进行其他配置,请参阅docs

If we now put the folder something into /var/www and inside it index.php with some Hello World content, it should all work. But in this case, it’ll output the contents of the PHP file as text. We need to configure the rest of the VirtualHost’s parameters as usual. I’ll paste my PuPHPet version below – your configuration may vary.

如果我们现在把文件夹something进入/var/www和里面index.php一些的Hello World的内容,就应该所有的工作。 但是在这种情况下,它将以文本形式输出PHP文件的内容。 我们需要像往常一样配置其余VirtualHost的参数。 我将在下面粘贴我的PuPHPet版本-您的配置可能会有所不同。

UseCanonicalName Off
<VirtualHost *:80>
  ServerName vhosts.fqdn
  ServerAlias *.local.com

  VirtualDocumentRoot /var/www/%1

  <Directory ~ "/var/www/.*">
    Options Indexes FollowSymlinks MultiViews
    AllowOverride All
    Require all granted
    
    <FilesMatch "\.php$">
      Require all granted
      SetHandler proxy:fcgi://127.0.0.1:9000
      
    </FilesMatch>

  </Directory>
</VirtualHost>

Now, if you reload Apache configuration with sudo service apache2 restart or whichever command works on your distribution, you should be able to access something.local.com in your browser and once again see it working if you put some PHP files into var/www/something/public.

现在,如果您使用sudo service apache2 restart加载Apache配置,或者您的发行版上运行的任何命令都可以,那么您应该能够在浏览器中访问something.local.com ,如果将一些PHP文件放入var/www/something/public它再次可以正常工作。 var/www/something/public

可选:dnsmasq (Optional: dnsmasq)

Optionally, if you’re on Linux or OS X, you can install dnsmasq.

或者,如果您使用的是Linux或OS X,则可以安装dnsmasq

Dnsmasq is a tool which, among other things, forwards a range of URLs to a given IP. It’s like regex support for /etc/hosts. With this tool, you can set all URLs ending in .local.com or whatever else you choose to redirect to your virtual machine’s IP or to your localhost. This means you never have to edit your hosts file again – whenever you start a new project, your URLs and Vhosts can be assumed ready and you can start working right away, minimizing devops dramatically.

Dnsmasq是一种工具,它可以将一系列URL转发到给定IP。 就像正则表达式对/etc/hosts支持。 使用此工具,您可以设置所有.local.com结尾的.local.com或任何其他选择的重定向到虚拟机IP或本地主机的URL。 这意味着您无需再编辑hosts文件-每当您开始一个新项目时,您就可以假定您的URL和Vhosts已经准备就绪,您可以立即开始工作,从而最大程度地减少开发人员的工作量。

On OS X with the Homebrew package manager:

在带有Homebrew软件包管理器的OS X上:

brew install dnsmasq

On your Linux distributions, download the tarball.

在Linux发行版上,下载tarball

If you want to further automate this, you can add dnsmasq as a Vagrant plugin.

如果您想进一步自动化,可以将dnsmasq添加为Vagrant插件

To set up dnsmasq to forward a URL pattern to your IP, and to set up your OS to forward all URL calls to dnsmasq so it can actually do this, see this excellent guide.

要将dnsmasq设置为将URL模式转发到IP,并将OS设置为将所有URL调用转发给dnsmasq,以便实际上可以执行此操作,请参阅此优秀指南

结论 (Conclusion)

In this tutorial, we’ve learned how to automate that part of devops we all regularly deal with – setting up new Vhosts and their domains. It’s only a couple of minutes on every project, especially with packages like Homestead Improved, but it’s still a couple of minutes – and being able to quickly switch into another mock project for testing that one script you just thought of or need to try out is priceless for one’s workflow.

在本教程中,我们学习了如何使我们大家定期处理的部分devops自动化–设置新的Vhost及其域。 每个项目只有几分钟的时间,尤其是像Homestead Improvement这样的软件包,但仍然只有几分钟的时间-能够快速切换到另一个模拟项目来测试您刚刚想到或需要尝试的脚本是对一个人的工作流程无价之宝。

Did this tutorial help you? Would you have liked to get more information on certain topics? Let us know!

本教程对您有帮助吗? 您想获得有关某些主题的更多信息吗? 让我们知道!

翻译自: https://www.sitepoint.com/set-automatic-virtual-hosts-nginx-apache/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值