在使用 CodeIgniter 时正确配置 Mod 重写


Properly Configuring Mod Rewrite while using CodeIgniter

我发现了几个关于CodeIgniter和mod重写问题的相关问题,但是,我还没有找到解决我目前遇到的问题的方法。

我目前有:mywebsiteurl.netfirms.com/mywebsite/index.php/admin/login

我想实现的是从 URL 中删除索引.php如下所示:mywebsiteurl.netfirms.com/mywebsite/admin/login

然而,在尝试了我在StackOverflow上找到的几个修复程序后,我最终偶然发现了一个很好的小指南。

我已经修改了我的模组重写,如下所示:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
### Canonicalize codeigniter URLs
# If your default controller is something other than
# "welcome" you should probably change this
RewriteRule ^(home(/index)?|index('.php)?)/?$ / [L,R=301]
RewriteRule ^(.*)/index/?$ $1 [L,R=301]
# Removes trailing slashes (prevents SEO duplicate content issues)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ $1 [L,R=301]
# Enforce www
# If you have subdomains, you can add them to 
# the list using the "|" (OR) regex operator
# RewriteCond %{HTTP_HOST} !^(www|subdomain) [NC]
# RewriteRule ^(.*)$ http://www.domain.tld/$1 [L,R=301]
# Enforce NO www
#RewriteCond %{HTTP_HOST} ^www [NC]
#RewriteRule ^(.*)$ http://domain.tld/$1 [L,R=301]
###
# Removes access to the system folder by users.
# Additionally this will allow you to create a System.php controller,
# previously this would not have been possible.
# 'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [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 index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

# Without mod_rewrite, route 404's to the front controller
ErrorDocument 404 /index.php

即使在实现此 mod-rewrite 之后,如果我尝试访问 404 mywebsiteurl.netfirms.com/mywebsite/admin/login,我也会收到 404 错误。如果我去 mywebsiteurl.netfirms.com/mywebsite/index.php/admin/login 我就可以很好地加载页面。

我的问题归结为如何为代码点火器正确配置我的模组重写?也许我缺少一些设置?我对 mod-rewrite 不够熟悉,无法真正知道哪里出了问题。

我还应该提到我已经在我的代码点火器配置文件中进行了更改。

$config['index_page'] = '';

有没有人对我在这里可能做错了什么有任何想法?

提前谢谢。

我的htaccess文件位于public_html/mywebsite目录中,可通过 mywebsiteurl.netfirms.com/mywebsite/访问

您需要更新重写基础和另一个规则:

RewriteBase /

需要:

RewriteBase /mywebsite/

而这条线

RewriteRule ^(home(/index)?|index('.php)?)/?$ / [L,R=301]

需要

RewriteRule ^(home(/index)?|index('.php)?)/?$ /mywebsite/ [L,R=301]

这需要删除前导斜杠:

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

这样就像:

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

当规则的目标中没有前导斜杠时,它是一个相对 URI 路径,并使用基来确定根。由于您的内容在mywebsite,因此基础需要反映这一点。

我想我刚刚为您的问题找到了更好的解决方案,这很简单。在 CodeIgniter 的配置文件中,留空index_page并base_url:

$config['base_url']   = '';
$config['index_page'] = '';

CodeIgniter 将自己计算出您的基本路径,并且不会在 uri 中使用 index.php 段。

然后在您的 .htaccess 文件中,应用指令将除文件夹和文件名以外的所有 url 重定向到您的索引.php :

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

这将完成这项工作,并且在更改项目根文件夹时不必更改任何配置文件中的任何内容。

希望有帮助。