Removing index.php from website URLs

2019-02-25 12:22发布

问题:

I am using the Kohana framework (but I think it's irrelevant for this question) and pages can be accessed like so

http://www.example.com/articles/
http://www.example.com/index.php/articles/

Now, as a rule of thumb, I generally try and tweak my .htaccess to only allow one way in for a page, and silently redirect other common ways.

Essentially, in the 1st URL above, the address is actually internally redirected to the 2nd example.

What I want to do, is to force any URLs of the 2nd type to turn into URLs of the first type. I'm not often confident in .htaccess, and my first attempt is throwing some unexpected results (like endless loops on occasion)

Here is what I've came up with

RewriteRule ^index\.php/(.*) $1 [NC,L,R=301]

Can anyone tell me what I'm doing wrong, and if you've also ran into this problem, how have you solved it?

EDIT

I've decided to post my entire .htaccess so all of my redirects can be examined.

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /~toberua/


# file not found page
    ErrorDocument 404 /404/
    ErrorDocument 403 /403/

# get people out of my directories
    Options -Indexes

# default page to load
    DirectoryIndex index.php

# add trailing slash if missing
    RewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ $1/ [NC,R=301,L]

# redirect /favicon.ico requests
     RewriteCond %{REQUEST_URI} !^/images/layout/favicon\.ico [NC]
     RewriteCond %{REQUEST_URI} favicon\.(gif|ico|png|jpe?g) [NC]
     RewriteRule (.*) images/layout/favicon.ico [R=301,L]

# send /home back to TLD
     RewriteRule home/ $1  [NC,R=301,L]

# ensure there is no /index.php in the address bar
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\.php\ HTTP/
    RewriteRule ^(.*)index\.php$ $1 [R=301,L] # this was my attempt to stop /dir/index.php and make it simply /dir/

    RewriteRule ^index\.php/(.*) $1 [NS,NC,L,R=301]

# Protect application and system files from being viewed
RewriteRule ^(application|modules|system) - [F,L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT,L]

回答1:

Try this:

RewriteRule ^index\.php/(.*) $1 [NS,NC,L,R=301]

What you're not processing is that all requests are subject to rewriting, and when you do a rewrite it generate a subrequest -- which is also subject to rewriting. So you wind up rewriting /articles to /index.php/articles, then in the subrequest that that issue, you rewrite /index.php/articles to /articles and generate a new request for the 301 redirect, on and on. Adding the NS flag will make this rule not operate on subrequests, which I think should fix your problem, unless you're also doing a 301 on the /articles -> /index.php/articles rewrite (but that would be madness).