使用.htaccess文件删除.php文件扩展名 [英] Removing .php file extension with .htaccess file

查看:67
本文介绍了使用.htaccess文件删除.php文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望www.example.com/about.php只是www.example.com/about

I want www.example.com/about.php to just be www.example.com/about

我创建了一个.htaccess文件,并将其放在服务器的根目录中. 我正在使用linux共享主机. PHP 5.2版

I created an .htaccess file and placed it in the root of my server. I am using linux shared hosting. PHP version 5.2

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

该代码似乎应该可以正常工作,但是由于某些原因,它不能正常工作.当我尝试导航到不带.php扩展名的页面时,出现404错误.

It seems that this code should work properly, but for some reason it does not. I get a 404 error when I try to navigate to a page without the .php extension.

这也是我的标记:

<nav>
        <div class="container">
            <ul>
                <li><a href="index.php" <?php if (strpos($_SERVER['PHP_SELF'], 'index.php')) echo 'class="current-nav"';?>>home</a></li>
                <li><a href="about.php">about</a></li>
                <li><a href="services">our services</a></li>
                <li><a href="portfolio" <?php if (strpos($_SERVER['PHP_SELF'], 'portfolio.php')) echo 'class="current-nav"';?>>portfolio</a></li>
                <li><a href="testimonials" <?php if (strpos($_SERVER['PHP_SELF'], 'testimonials.php')) echo 'class="current-nav"';?>>testimonials</a></li>
                <!--<li><a href="#">client area</a></li>-->
                <li><a href="contact" <?php if (strpos($_SERVER['PHP_SELF'], 'contact.php')) echo 'class="current-nav"';?>>Contact</a></li>
                <li><a href="order" <?php if (strpos($_SERVER['PHP_SELF'], 'order.php')) echo 'class="current-nav"';?>><strong>Free Quote</strong></a></li>
            </ul>
        </div>
    </nav><!--/navigation--> 

您可以看到我尝试在链接中使用php扩展名,也尝试了不使用它.带有php扩展名的链接转到该页面,但请不要删除该扩展名.

You can see I tried using the php extension in the link and also tried without. The links with the php extension go to the page, but don't remove the extension.

我做了一个测试,看是否通过添加一些垃圾并返回500错误来启用了module_rewrite.

I did a test to see if module_rewrite was enabled by putting in some garbage and returning a 500 error.

推荐答案

使用以下代码隐藏/删除.php扩展名:

Use this code for hiding/removing .php extension:

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

## hide .php extension
# 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
RewriteRule ^ %{REQUEST_URI}.php [L]

这篇关于使用.htaccess文件删除.php文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆