【问题标题】:Better method for Rewrite URLs重写 URL 的更好方法
【发布时间】:2016-10-01 13:50:31
【问题描述】:

哪种方法更适合重写 URL

(一)。使用 htaccess 文件并在其中使用正则表达式,用于重写规则

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^users/(\d+)*$ ./profile.php?id=$1
RewriteRule ^threads/(\d+)*$ ./thread.php?id=$1

RewriteRule ^search/(.*)$ ./search.php?query=$1

(b)。 使用 htacess 文件将每个 url 重定向到 index.php,然后使用 PHP 进行进一步的重定向。

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

 RewriteRule ^.*$ ./index.php

之后每个 url 都可以由 index.php 使用 $_SERVER['REQUEST_URI'] 处理,我们可以使用 require() 语句加载特定文件

在安全和速度的基础上,哪种方法更好?

【问题讨论】:

    标签: php apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    这个方法比较完美,在你的.htaccess文件中使用下面的代码,并在你的脚本中定义你想要访问的目录,例如:js、css或上传文件夹

    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|assets|**data**|**live**|**css**|**js**|**images**).
    

    如果你想把你的脚本放在文件夹中,你必须在 /index.php 之前的第二个语句中定义文件夹名称,例如我们

    RewriteRule ^(.*)$ **anyFolderName**/index.php/$1 [PT,L]
    

    确保你没有放任何多余的空格、字母或输入,否则重写模型将不会执行。

    注意:还要确保从服务器/apache/apache 模块/rewrite_module 运行/检查 rewrite_module。

    <IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On
    
    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /
    
    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)
    
    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]
    
    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|assets)
    
    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]
    
    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ /index.php/$1 [PT,L]
    </IfModule>
    

    【讨论】:

      【解决方案2】:

      这取决于您的要求。如果您已经创建了这些 php 文件,那么将第一个 .htaccess 重构为像这样的单个规则应该可以正常工作:

      Options +FollowSymLinks
      RewriteEngine On
      
      RewriteCond %{SCRIPT_FILENAME} !-d
      RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
      RewriteRule ^([\w-]+)/(\d+)/?$ $1.php?id=$2 [L,QSA]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-02
        • 2019-10-28
        • 1970-01-01
        • 1970-01-01
        • 2015-11-09
        • 1970-01-01
        相关资源
        最近更新 更多