简体   繁体   中英

Redirect all traffic to index.php using mod_rewrite

I'm trying to build a url shortener, and I want to be able to take any characters immediately after the domain and have them passed as a variable url. So for example

would become

Here's what I have for mod_rewrite right now, but I keep getting a 400 Bad Request:

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

Try replacing ^(.*) with ^(.*)$

RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

Edit: Try replacing index.php with /index.php

RewriteRule ^(.*)$ /index.php?url=$1 [L,QSA]

ByTheWay don't forget to enable mod rewrite,in apache on ubuntu

sudo a2enmod rewrite 

and then restart apache2

sudo /etc/init.d/apache2 restart

edit: it is an old question that helped me but I lost hours testing my apache2.conf file on one side and .htaccess file on the other side and still no light.

To rewrite all requests to /index.php ,you can use :

RewriteEngine on


RewriteCond %{REQUEST_URI} !^/index.php$
RewriteRule ^(.+)$ /index.php?url=$1 [NC,L]

The RewriteCondition RewriteCond %{REQUEST_URI} !^/index.php$ is important as it excludes the rewrite destination we are rewriting to and prevents infinite looping error.

Check under Apache modules and make sure that rewrite-module is enabled. I had a similar issue and it was resolved by enabling the rewrite-module.

in the framework folder create an .htaccess file with the following contents

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule ^$ public/ [L]
    RewriteRule (.*) public/$1 [L]
</IfModule>

then in the framework/public folder create an .htaccess file with the contents

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?url=$1 [L]
</IfModule>

by adding the .htaccess file as above we can make the URL on the website more user-friendly. For example if we write a URL like

http://google.com/asdf

will be converted to

http://google.com?url=asdf

for test purposes, we create a php index.php file in a public folder with the following content

<?php
    echo $_GET['url'];
?>

if when run in a browser using the URL above the result is 404 not found, most likely mod_rewrite has not been enabled as in step 1. if the result is 500 Internal Server Error, there may be an error in writing .htaccess

在不使用RewriteCond情况下尝试一下。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM