douye1940 2013-09-11 21:51
浏览 36
已采纳

PHP / .htaccess:从url中删除php扩展

I was using .htaccess code to remove .php extension for all my web pages. Here's the code I use:

RewriteEngine On
RewriteCond /%{REQUEST_FILENAME}.php -f
RewriteRule ^([a-zA-Z0-9_-\s]+)/$ /$1.php

It doesn't seem to work. I think I'm missing something. When I type www.mysite.com/about/ to get www.mysite.com/about.php it returns error 404 (page not found). Can someone please shed some light.

Thanks, Paul G.

  • 写回答

2条回答 默认 最新

  • duanph1978 2013-09-11 22:16
    关注
    Options +FollowSymLinks -MultiViews
    
    RewriteEngine On
    RewriteBase /
    
    # If folder does not exist
    RewriteCond %{REQUEST_FILENAME} !-d
    # and file exist
    RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
    # uncomment the below rule if you want the "/" to be required 
    # otherwise leave as is
    # RewriteRule ^([^/]+)/$ $1.php [L]
    # internally show the content of filename.php
    RewriteRule ^([^/]+)/?$ $1.php [L]
    

    The above rule will:

    1. will not redirect if a folder exist
    2. will not redirect if the file does not exist
    3. will redirect what comes before the / if one is present as the file name

    So it will work for all these examples:

    http://domain.com/about/
    http://domain.com/about
    http://domain.com/contact/
    http://domain.com/contact
    

    If you want you can remove the ?, like the commented rule, to make it accept only URL's that end with a /.

    http://domain.com/about/
    http://domain.com/contact/
    

    Now these are important step for the above to work:

    1. It must go into the .htaccess on your root folder for example /home/youraccount/public_html/.htaccess
    2. The Options before the rewrite rule are very important specially -MultiViews
    3. The file must exist on the same place the .htaccess is for example in your case the about.php file
    4. The PHP must be working obviously.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀