在Apache的.htaccess中遇到了麻烦的故事

使用.htaccess,將php文件的擴展名去除,實現以下目標:
從域名/index.php變為域名/index,達到可以訪問的效果。但遇到了問題,下面將討論解決辦法並做個備忘錄。

进行配置文件的更改,以便可以使用.htaccess。

请将设置文件和目录的地方更改一下。

$ sudo vim /etc/apache2/sites-available/****.conf

<Directory "/home/name/public_html/">
                Options Indexes FollowSymLinks
                AllowOverride None
                Require all granted
</Directory>

将希望使用.htaccess进行配置的目录设置中的AllowOverride从None更改为All。

<Directory "/home/name/public_html/">
                Options Indexes FollowSymLinks
                AllowOverride All
                Require all granted
</Directory>

将.htaccess文件放置

$ vim ~/public_html/.htaccess

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

创建并访问文件

<html>
 <body>
 <?php
   echo "拡張子なしでアクセスできるかのテスト";
 ?>
 </body>
</html>

我尝试创建这样一个文件并访问,无论是在域名/index还是域名/index,都会返回500错误。

进行调查以查明原因。

$ less /etc/var/log/apache2/error.log

[Mon Apr 11 22:49:20.736625 2016] [core:alert] [pid 19815]  
/home/name/public_html/.htaccess: Invalid command 'RewriteEngine', 
perhaps misspelled or defined by a module not included in the server configuration

找到一个看起来像是缺少模块的错误。
由于找不到RewriteEngine,所以请启用mod_rewrite。更详细的信息请参考这里。

$ cd /etc/apache2/mods-available/
$ sudo a2enmod rewrite
$ sudo service apache2 restart

重新访问

スクリーンショット 2016-04-11 23.33.32.png

最终

如果遇到困难,只需查看错误日志并搜索一下,通常问题就能解决。

bannerAds