【问题标题】:Hiding .php extensions in URL not working在 URL 中隐藏 .php 扩展名不起作用
【发布时间】:2014-12-29 15:02:23
【问题描述】:

我试图在我的网站上隐藏 PHP 扩展,例如,如果我转到 http://code-up.nl/contact,则将加载 http://code-up.nl/contact.php 文件。我的服务器上有几个域。在网站的根目录(位于 /var/www/code-up.nl)我有以下 .htaccess 文件:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L]

在我的 apache 虚拟主机文件中,我将 AllowOverride 设置为 All:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName code-up.nl
    ServerAlias www.code-up.nl
    DocumentRoot /var/www/code-up.nl

    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>

    <Directory /var/www/code-up.nl/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

我认为一切正常,但当我转到 http://code-up.nl/contact 时仍然收到错误 404。我已经寻找了一个解决方案并尝试了很多东西,但它就是行不通。有人可以帮忙吗?

【问题讨论】:

  • mod_rewrite 已安装并启用。我在 phpinfo() 的输出中检查了它
  • RewriteRule ^ %{REQUEST_FILENAME}.php [L]

标签: php apache .htaccess url mod-rewrite


【解决方案1】:

在 DOCUMENT_ROOT 下的 .htaccess 中试试这个:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

【讨论】:

  • 现在可以使用了!但我并不完全了解导致问题的确切原因。你能解释一下吗?非常感谢!
  • 我不会解释 .htaccess 是如何工作的,但在这种情况下,您只需在外部将所有 *.php 重定向到 *,并在内部将 * 重定向到 *.php 以获得好的页面。 .. 而不是 404
猜你喜欢
  • 2011-09-08
  • 1970-01-01
  • 2018-03-14
  • 2021-01-23
  • 2012-04-19
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
相关资源
最近更新 更多