【问题标题】:using htaccess to remove .php from URL使用 htaccess 从 URL 中删除 .php
【发布时间】:2013-05-09 10:56:59
【问题描述】:

我的网址:http://localhost/test.php

我正在使用:

.htaccess:

RewriteEngine On 
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

PHP:

$url = $_GET['url'];
echo var_dump($url);

但我得到的只是$url:NULL NULL NULL NULL NULL NULL

【问题讨论】:

    标签: php apache .htaccess url-rewriting xampp


    【解决方案1】:

    编辑:调整为处理重定向和重写。

    RewriteEngine On 
    RewriteBase /
    
    # Redirect .php URLs to rewritten URLs
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ^(.+)\.php$ $1 [L,QSA,R=301]
    
    # Rewrite URLs for processing by router (index.php)
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ^(.+)$ index.php?url=$1 [QSA,L,NC]
    

    您应该排除 RewriteCond %{REQUEST_FILENAME} !-d 条件,因为如果您的 URL 匹配它,它将尝试访问目录。在进行 url 重写时可能不理想。

    index.php

    $url = isset($_GET['url']) ? $_GET['url'] : null;
    var_dump($url);
    

    【讨论】:

    • 这很有效,非常感谢。很奇怪吧?嗯,我要比较格式,看看我哪里出错了。再次感谢你,我给你打勾:)
    • 干杯。请注意我刚刚在最后添加的评论。您可能希望摆脱目录匹配条件。
    • 如果您传递 get params,QSA 标志可能会对 URL 产生一些奇怪的影响
    • @user2218297 - 您可能永远不想进行目录匹配。这就是为什么。假设您的站点中有一个名为 /images 的目录 - 如果您有对站点的请求,例如 mysite.com/images ,它将尝试访问图像目录而不是 index.php?url=images - 前者可能永远不会你想要什么
    • 了解一些东西。如果文件存在于您的 webroot 中,htaccess 将不会重定向。您可能希望将 test.php 放在您的 webroot 之外,例如如果您的 www 在 /var/www 中,请将 test.php 放在名为 /var/modules 的目录中。然后让 /var/www/index.php 做include("/var/modules/{$url}.php"); 加载外部模块
    【解决方案2】:

    我只是想把它留给未来的用户。这会从 URLS 中删除 HTML 和 PHP 扩展。

    #example.com/page will display the contents of example.com/page.html
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^(.+)$ $1.html [L,QSA]
    
    #301 from example.com/page.html to example.com/page
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
    RewriteRule ^(.*)\.html$ /$1 [R=301,L]
    
    ## don't touch /forum URIs
    RewriteRule ^forums/ - [L,NC]
    
    ## hide .php extension snippet
    
    # To externally redirect /dir/foo.php to /dir/foo
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
    RewriteRule ^ %1 [R,L]
    
    # To internally forward /dir/foo to /dir/foo.php
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.*?)/?$ $1.php [L]
    

    【讨论】:

      猜你喜欢
      • 2013-04-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      • 2021-10-02
      • 2015-01-20
      • 2021-12-11
      相关资源
      最近更新 更多