重写URL-Apache-htaccess

时间:2018-10-13 21:44:11

标签: apache .htaccess codeigniter mod-rewrite

我正在将现有网站迁移到Codeigniter,因此需要重新编写URL的帮助。

我需要用新的URL映射旧的URL,以便从搜索引擎结果访问网站的人被重定向到匹配的新URL,否则他们将得到页面未找到的错误。

大多数旧网址都采用这种格式,例如

/page.php?id=5 or /page.php?id=180&t=78
/data.php?token=GH45LK
/faqs.php?k=98#section2

它们匹配的新URL是

/page/5 or I will be happy with /page?id=5&whatever=xyz too
/data/GH45LK
/faqs/98#section2

这是我当前对CodeIgniter的.htaccess

# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # If you installed CodeIgniter in a subfolder, you will need to
    # change the following line to match the subfolder you need.
    # http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
    RewriteBase /

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Rewrite "www.example.com -> example.com"
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    # Checks to see if the user is attempting to access a valid file,
    # such as an image or css document, if this isn't true it sends the
    # request to the front controller, index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

    # Ensure Authorization header is passed along
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

我在RewriteBase /行之后尝试了类似的操作

RewriteRule ^data\.php\?token=(.*)?$ data/=$1 [R=301,L]

,但不能确定我是否正确,因为它无法正常工作。

您能帮我弄对吗?谢谢

1 个答案:

答案 0 :(得分:1)

(func2 (list 1 2 3) (list 4) 5) ;; ((1 2 3) (4) 5) ;; the result of (FUNC1 '(1 2 3) '(4) '5) 不能那样工作:它仅测试URL的 path 部分。对于所有其他部分(域,查询字符串等),您需要使用RewriteRule和相应的变量(RewriteCond,用于查询字符串/此处)。

%{QUERY_STRING}

我认为RewriteCond %{QUERY_STRING} (?:^|&)id=(\d+) RewriteRule ^page\.php$ /page/%1 [L,R=permanent] RewriteCond %{QUERY_STRING} (?:^|&)token=([^&]+) RewriteRule ^data\.php$ /data/%1? [L,R=permanent] RewriteCond %{QUERY_STRING} (?:^|&)k=(\d+) RewriteRule ^faqs\.php$ /faqs/%1? [L,R=permanent] 发生错误,因为您在RewriteCond %{HTTPS} !=on而不是http://上重定向,这将导致无限循环。

还要注意,锚点(在您的示例中为#section2)没有发送到服务器(因此无法重写)。