Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

regex - Removing .php file extension with .htaccess file

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

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

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.

Here's my markup too:

<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--> 

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...