debian apache_如何在Debian 10上使用mod_rewrite为Apache重写URL

debian apache

介绍 (Introduction)

Apache’s mod_rewrite module lets you rewrite URLs in a cleaner fashion, translating human-readable paths into code-friendly query strings. It also lets you rewrite URLs based on conditions.

Apache的mod_rewrite模块使您可以以一种更简洁的方式重写URL,将人类可读的路径转换为代码友好的查询字符串。 它还使您可以根据条件重写URL。

An .htaccess file lets you create and apply rewrite rules without accessing server configuration files. By placing the .htaccess file in the root of your web site, you can manage rewrites on a per-site or per-directory basis.

.htaccess文件使您可以创建和应用重写规则,而无需访问服务器配置文件。 通过将.htaccess文件放置在网站的根目录中,可以按站点或按目录管理重写。

In this tutorial, you’ll enable mod_rewrite and use .htaccess files to create a basic URL redirection, and then explore a couple of advanced use cases.

在本教程中,您将启用mod_rewrite并使用.htaccess文件创建基本的URL重定向,然后探究几个高级用例。

先决条件 (Prerequisites)

To follow this tutorial, you will need:

要遵循本教程,您将需要:

步骤1 —启用mod_rewrite (Step 1 — Enabling mod_rewrite)

In order for Apache to understand rewrite rules, we first need to activate mod_rewrite. It’s already installed, but it’s disabled on a default Apache installation. Use the a2enmod command to enable the module:

为了让Apache理解重写规则,我们首先需要激活mod_rewrite 。 它已经安装,但是在默认的Apache安装中已禁用。 使用a2enmod命令启用模块:

  • sudo a2enmod rewrite

    sudo a2enmod重写

This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache:

这将激活模块或警告您该模块已启用。 要使这些更改生效,请重新启动Apache:

  • sudo systemctl restart apache2

    sudo systemctl重新启动apache2

mod_rewrite is now fully enabled. In the next step we will set up an .htaccess file that we’ll use to define rewrite rules for redirects.

现在已完全启用mod_rewrite 。 在下一步中,我们将设置一个.htaccess文件,该文件将用于定义重定向的重写规则。

第2步-设置.htaccess (Step 2 — Setting Up .htaccess)

An .htaccess file allows us to modify our rewrite rules without accessing server configuration files. For this reason, .htaccess is critical to your web application’s security. The period that precedes the filename ensures that the file is hidden.

.htaccess文件使我们可以修改重写规则,而无需访问服务器配置文件。 因此, .htaccess对Web应用程序的安全性至关重要。 文件名之前的时间可确保文件被隐藏。

Note: Any rules that you can put in an .htaccess file can also be put directly into server configuration files. In fact, the official Apache documentation recommends using server configuration files instead of .htaccess thanks to faster processing times.

注意:可以放入.htaccess文件的任何规则也可以直接放入服务器配置文件中。 实际上,由于处理速度更快, Apache官方文档建议使用服务器配置文件而不是.htaccess

However, in this simple example, the performance increase will be negligible. Additionally, setting rules in .htaccess is convenient, especially with multiple websites on the same server. It does not require a server restart for changes to take effect or root privileges to edit rules, simplifying maintenance and the process of making changes with an unprivileged account. Popular open-source software like Wordpress and Joomla rely on .htaccess files to make modifications and additional rules on demand.

但是,在这个简单的示例中,性能提升将是微不足道的。 此外,在.htaccess设置规则很方便,尤其是在同一服务器上有多个网站时。 它不需要重新启动服务器即可使更改生效,也不需要root用户权限来编辑规则,从而简化了维护以及使用无特权帐户进行更改的过程。 流行的开源软件(如Wordpress和Joomla)依靠.htaccess文件进行修改和按需附加规则。

Before you start using .htaccess files, you’ll need to set up and secure a few more settings.

在开始使用.htaccess文件之前,您需要设置并保护更多设置。

By default, Apache prohibits using an .htaccess file to apply rewrite rules, so first you need to allow changes to the file. Open the default Apache configuration file using nano or your favorite text editor:

默认情况下,Apache禁止使用.htaccess文件应用重写规则,因此首先您需要允许对该文件进行更改。 使用nano或您喜欢的文本编辑器打开默认的Apache配置文件:

  • sudo nano /etc/apache2/sites-available/000-default.conf

    须藤纳米/etc/apache2/sites-available/000-default.conf

Inside that file, you will find a <VirtualHost *:80> block starting on the first line. Inside of that block, add the following new block so your configuration file looks like the following. Make sure that all blocks are properly indented:

在该文件内,您会发现从第一行开始的<VirtualHost *:80>块。 在该块内部,添加以下新块,以便您的配置文件如下所示。 确保所有块都正确缩进:

/etc/apache2/sites-available/000-default.conf
/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
    <Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    . . .
</VirtualHost>

Save and close the file. If you used nano, do so by pressing CTRL+X, Y, then ENTER.

保存并关闭文件。 如果您使用过nano ,请按CTRL+XY ,然后按ENTER

Then, check your configuration:

然后,检查您的配置:

  • sudo apache2ctl configtest

    须藤apache2ctl configtest

If there are no errors, restart Apache to put your changes into effect:

如果没有错误,请重新启动Apache以使更改生效:

  • sudo systemctl restart apache2

    sudo systemctl重新启动apache2

Now, create an .htaccess file in the web root:

现在,在Web根目录中创建一个.htaccess文件:

  • sudo nano /var/www/html/.htaccess

    须藤纳米/var/www/html/.htaccess

Add this line at the top of the new file to activate the rewrite engine.

在新文件的顶部添加此行以激活重写引擎。

/var/www/html/.htaccess
/var/www/html/.htaccess
RewriteEngine on

Save the file and exit.

保存文件并退出。

You now have an operational .htaccess file that you can use to govern your web application’s routing rules. In the next step, we will create a sample website file that we’ll use to demonstrate rewrite rules.

现在,您有了一个可操作的.htaccess文件,可用于管理Web应用程序的路由规则。 在下一步中,我们将创建一个示例网站文件,用于演示重写规则。

步骤3 —配置URL重写 (Step 3 — Configuring URL Rewrites)

Here, we will set up a basic URL rewrite which converts pretty URLs into actual paths to pages. Specifically, we will allow users to access http://your_server_ip/about, and display a page called about.html.

在这里,我们将设置一个基本的URL重写,它将漂亮的URL转换为页面的实际路径。 具体来说,我们将允许用户访问http:// your_server_ip /about ,并显示一个名为about.html的页面。

Begin by creating a file named about.html in the web root:

首先在网络根目录中创建一个名为about.html的文件:

  • sudo nano /var/www/html/about.html

    须藤nano /var/www/html/about.html

Copy the following HTML code into the file, then save and close it.

将以下HTML代码复制到文件中,然后保存并关闭它。

/var/www/html/about.html
/var/www/html/about.html
<html>
    <head>
        <title>About Us</title>
    </head>
    <body>
        <h1>About Us</h1>
    </body>
</html>

You can access this page at http://your_server_ip/about.html, but notice that if you try to access http://your_server_ip/about, you will see a 404 Not Found error. To access the page using /about instead, we’ll create a rewrite rule.

您可以通过http:// your_server_ip /about.html访问此页面,但是请注意,如果尝试访问http:// your_server_ip /about ,则会看到404 Not Found错误。 要使用/about来访问页面,我们将创建一个重写规则。

All RewriteRules follow this format:

所有RewriteRules遵循以下格式:

General RewriteRule structure
通用RewriteRule结构
RewriteRule pattern substitution [flags]
  • RewriteRule specifies the directive.

    RewriteRule指定指令。

  • pattern is a regular expression that matches the desired string from the URL, which is what the viewer types in the browser.

    pattern是一个正则表达式 ,它匹配URL中所需的字符串,这是查看器在浏览器中键入的内容。

  • substitution is the path to the actual URL, i.e. the path of the file Apache serves.

    substitution是实际URL的路径,即Apache服务的文件的路径。

  • flags are optional parameters that can modify how the rule works.

    flags是可选参数,可以修改规则的工作方式。

Let’s create our URL rewrite rule. Open up the .htaccess file:

让我们创建我们的URL重写规则。 打开.htaccess文件:

  • sudo nano /var/www/html/.htaccess

    须藤纳米/var/www/html/.htaccess

After the first line, add the following RewriteRule and save the file:

在第一行之后,添加以下RewriteRule并保存文件:

/var/www/html/.htaccess
/var/www/html/.htaccess
RewriteEngine on
RewriteRule ^about$ about.html [NC]

In this case, ^about$ is the pattern, about.html is the substitution, and [NC] is a flag. Our example uses a few characters with special meaning:

在这种情况下, ^about$是模式, about.html是替代, [NC]是标志。 我们的示例使用了一些具有特殊含义的字符:

  • ^ indicates the start of the URL, after your_server_ip/.

    ^表示URL的开头,在your_server_ip /

  • $ indicates the end of the URL.

    $表示URL的末尾。

  • about matches the string “about”.

    about与字符串“ about”匹配。

  • about.html is the actual file that the user accesses.

    about.html是用户访问的实际文件。

  • [NC] is a flag that makes the rule case insensitive.

    [NC]是使规则不区分大小写的标志。

You can now access http://your_server_ip/about in your browser. In fact, with the rule shown above, the following URLs will also point to about.html:

现在,您可以在浏览器中访问http:// your_server_ip /about 。 实际上,按照上面显示的规则,以下URL也将指向about.html

  • http://your_server_ip/about, because of the rule definition.

    http:// your_server_ip /about ,因为规则定义。

  • http://your_server_ip/About, because the rule is case insensitive.

    http:// your_server_ip /About ,因为该规则不区分大小写。

  • http://your_server_ip/about.html, because the original filename will always work.

    http:// your_server_ip /about.html ,因为原始文件名将始终有效。

However, the following will not work:

但是,以下操作无效:

  • http://your_server_ip/about/, because the rule explicitly states that there may be nothing after about, since the $ character appears after about.

    http:// your_server_ip /about/ ,因为该规则明确指出在about之后可能没有任何about ,因为$字符出现在about之后。

  • http://your_server_ip/contact, because it won’t match the about string in the rule.

    http:// your_server_ip /contact ,因为它与规则中的about字符串不匹配。

You now have an operational .htaccess file with a basic rule that you can modify and extend to your needs. In the following sections, we will show two additional examples of commonly used directives.

现在,您将具有基本规则的可操作.htaccess文件,您可以对其进行修改并扩展其需求。 在以下各节中,我们将显示两个常用指令的其他示例。

示例1 —使用RewriteRule简化查询字符串 (Example 1 — Simplifying Query Strings with RewriteRule)

Web applications often make use of query strings, which are appended to a URL using a question mark (?) after the address. Separate parameters are delimited using an ampersand (&). Query strings may be used for passing additional data between individual application pages.

Web应用程序通常使用查询字符串查询字符串在地址后使用问号( ? )附加到URL。 单独的参数使用与号( & )分隔。 查询字符串可用于在各个应用程序页面之间传递其他数据。

For example, a search result page written in PHP may use a URL like http://example.com/results.php?item=shirt&season=summer. In this example, two additional parameters are passed to the imaginary result.php application script: item, with the value shirt, and season with the value summer. The application may use the query string information to build the right page for the visitor.

例如,用PHP编写的搜索结果页面可能使用类似http://example.com/results.php?item=shirt&season=summer的URL。 在此示例中,向虚构的result.php应用程序脚本传递了两个附加参数: item的值是shirtseason的值是summer 。 应用程序可以使用查询字符串信息来为访问者构建正确的页面。

Apache rewrite rules are often employed to simplify such long and unpleasant links as the example above into friendly URLs that are easier to type and interpret visually. In this example, we would like to simplify the above link to become http://example.com/shirt/summer. The shirt and summer parameter values are still in the address, but without the query string and script name.

通常使用Apache重写规则将上述示例中的漫长而令人不愉快的链接简化为友好的URL ,这些URL易于键入和解释。 在此示例中,我们想简化以上链接,使其成为http://example.com/shirt/summershirtsummer参数值仍在地址中,但没有查询字符串和脚本名称。

Here’s one rule to implement this:

这是实现此规则的一条规则:

Simple substition
简单替代
RewriteRule ^shirt/summer$ results.php?item=shirt&season=summer [QSA]

The shirt/summer is explicitly matched in the requested address and Apache is told to serve results.php?item=shirt&season=summer instead.

shirt/summer在请求的地址中明确匹配,Apache被告知提供results.php?item=shirt&season=summer代替。

The [QSA] flags are commonly used in rewrite rules. They tell Apache to append any additional query string to the served URL, so if the visitor types http://example.com/shirt/summer?page=2 the server will respond with results.php?item=shirt&season=summer&page=2. Without it, the additional query string would get discarded.

[QSA]标志通常在重写规则中使用。 他们告诉Apache将任何其他查询字符串附加到所提供的URL,因此访问者是否键入http://example.com/shirt/summer? page=2 http://example.com/shirt/summer? page=2服务器将响应results.php?item=shirt&season=summer &page=2 。 没有它,其他查询字符串将被丢弃。

While this method achieves the desired effect, both the item name and season are hardcoded into the rule. This means the rule will not work for any other items, like pants, or seasons, like winter.

尽管此方法达到了预期的效果,但商品名称和季节都被硬编码到规则中。 这意味着该规则不适用于其他任何物品,例如pants或季节(例如winter

To make the rule more generic, we can use regular expressions to match parts of the original address and use those parts in a substitution pattern. The modified rule will then look like this:

为了使规则更通用,我们可以使用正则表达式来匹配原始地址的某些部分,并在替换模式中使用这些部分。 修改后的规则将如下所示:

Simple substition
简单替代
RewriteRule ^([A-Za-z0-9]+)/(summer|winter|fall|spring) results.php?item=$1&season=$2 [QSA]

The first regular expression group in parenthesis matches a string containing alphanumeric characters and numbers like shirt or pants and saves the matched fragment as the $1 variable. The second regular expression group in parentheses matches exactly summer, winter, fall, or spring, and similarly saves the matched fragment as $2.

括号中的第一个正则表达式组匹配包含字母数字字符和数字(如shirtpants的字符串,并将匹配的片段保存为$1变量。 括号中的第二个正则表达式组恰好匹配summerwinterfallspring ,并且类似地将匹配的片段保存为$2

The matched fragments are then used in the resulting URL in item and season variables instead of the hardcoded shirt and summer values we used before.

然后将匹配的片段用于itemseason变量中的结果URL中,而不是我们之前使用的硬编码shirtsummer值。

The above will convert, for example, http://example.com/pants/summer into http://example.com/results.php?item=pants&season=summer. This example is also future proof, allowing multiple items and seasons to be correctly rewritten using a single rule.

上面的代码会将例如http://example.com/pants/summer转换为http://example.com/results.php?item=pants&season=summer 。 这个示例也可以作为未来的证明,允许使用单个规则正确地重写多个项目和季节。

示例2 —使用RewriteConds通过逻辑添加条件 (Example 2 — Adding Conditions with Logic Using RewriteConds)

Rewrite rules are not necessarily always evaluated one by one without any limitations. The RewriteCond directive lets us add conditions to our rewrite rules to control when the rules will be processed. All RewriteConds abide by the following format:

重写规则不一定总是一一评估而没有任何限制。 RewriteCond指令使我们可以向重写规则中添加条件,以控制何时处理规则。 所有RewriteConds遵循以下格式:

General RewriteCond structure
通用RewriteCond结构
RewriteCond TestString Condition [Flags]
  • RewriteCond specifies the RewriteCond directive.

    RewriteCond指定RewriteCond指令。

  • TestString is the string to test against.

    TestString是要测试的字符串。

  • Condition is the pattern or condition to match.

    Condition是要匹配的模式或条件。

  • Flags are optional parameters that may modify the condition and evaluation rules.

    Flags是可选参数,可以修改条件和评估规则。

If a RewriteCond evaluates to true, the next RewriteRule will be considered. If it doesn’t, the rule will be discarded. Multiple RewriteConds may be used one after another, though all must evaluate to true for the next rule to be considered.

如果RewriteCond评估为true,则将考虑下一个RewriteRule 。 如果不是,该规则将被丢弃。 多个RewriteConds可以一个接一个地使用,尽管所有条件都必须评估为true才能考虑使用下一个规则。

As an example, let’s assume you would like to redirect all requests to non-existent files or directories on your site back to the home page instead of showing the standard 404 Not Found error page. This can be achieved with following conditions rules:

例如,假设您想将所有请求重定向到站点上不存在的文件或目录,返回到首页,而不是显示标准的404 Not Found错误页面。 这可以通过以下条件规则来实现:

Redirect all requests to non-existent files and directories to home page
将所有请求重定向到不存在的文件和目录到主页
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /

With the above:

具有以上内容:

  • %{REQUEST_FILENAME} is the string to check. In this case, it’s the requested filename, which is a system variable available for every request.

    %{REQUEST_FILENAME}是要检查的字符串。 在这种情况下,它是请求的文件名,这是每个请求都可以使用的系统变量。

  • -f is a built-in condition which verifies if the requested name exists on disk and is a file. The ! is a negation operator. Combined, !-f evaluates to true only if the specified name does not exist or is not a file.

    -f是一个内置条件,它会验证请求的名称是否在磁盘上并且是文件。 ! 是一个否定运算符。 仅当指定的名称不存在或不是文件时, !-f组合起来评估为true。

  • Similarly, !-d evaluates to true only if the specified name does not exist or is not a directory.

    同样, !-d仅在指定的名称不存在或不是目录时才为true。

The RewriteRule on the final line will come into effect only for requests to non-existent files or directories. The RewriteRule itself is very simple and redirects every request to the / website root.

最后一行的RewriteRule仅对对不存在的文件或目录的请求生效。 RewriteRule本身非常简单,它将每个请求重定向到/网站根目录。

结论 (Conclusion)

mod_rewrite lets you create human-readable URLs. In this tutorial, you learned how to use the RewriteRule directive to redirect URLs, including ones with query strings. You also learned how to conditionally redirect URLs using the RewriteCond directive.

mod_rewrite使您可以创建易于阅读的URL。 在本教程中,您学习了如何使用RewriteRule指令重定向URL,包括带有查询字符串的URL。 您还学习了如何使用RewriteCond指令有条件地重定向URL。

If you’d like to learn more about mod_rewrite, take a look at Apache’s mod_rewrite Introduction and Apache’s official documentation for mod_rewrite.

如果您想了解有关mod_rewrite更多信息,请查看Apache的mod_rewrite简介Apache的mod_rewrite官方文档

翻译自: https://www.digitalocean.com/community/tutorials/how-to-rewrite-urls-with-mod-rewrite-for-apache-on-debian-10

debian apache

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值