这可以单独使用 Apache 配置(httpd.conf 或 apache2.conf)中的语言/内容协商以及重写规则。不需要使用.htaccess 文件。
在 apache2.conf 文件(或 httpd.conf)中添加 Multiviews 指令、MultiviewsMatch 指令和重写规则:
<Directory /var/www/html>
Options Indexes FollowSymLinks Multiviews
AllowOverride None
Require all granted
RewriteEngine On
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]
<Files "*.php">
MultiviewsMatch Any
</Files>
</Directory>
然后保存文件并重启Apache sudo systemctl restart apache2
如果稍后在 httpd.conf 中指定 Options 指令,则必须为每个站点重复 Multiviews 指令:
<Directory /var/www/html/chocolate.com/>
Options FollowSymLinks Multiviews
AllowOverride All
Require all granted
</Directory>
<Directory /var/www/html/vanilla.com/>
Options FollowSymLinks Multiviews
AllowOverride All
Require all granted
</Directory>
如果您已经以多种语言提供服务,这不会对内容协商产生不利影响。例如,将 example.com/home.php 替换为
home.en.php
主页.fr.php
主页.de.php
然后在apache2.conf中:
AddLanguage fr .fr
AddLanguage de .de
AddLanguage en .en
LanguagePriority fr de en
ForceLanguagePriority Fallback
仍会协商您的语言,但 php 扩展名不会出现在 URL 中。