Cainã
Cainã

Reputation: 955

How to use .htaccess to rewrite all pages to a simple URL?

I have the following situation. I want to point all URLs like this:

http://localhost/mypage

To a long URL, just like this:

http://localhost/index.php?&page=mypage

And then in PHP do something like this:

include 'pages/' . $_GET['page'] . '.php';

I have tried the following but I get some errors.

RewriteRule ^(.+)$ index.php?&page=$1 [NC]

Is there any way to do this without listing all pages in .htaccess file?

Upvotes: 0

Views: 957

Answers (4)

Martin Bean
Martin Bean

Reputation: 39389

Try this:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1 [L]

So if you request http://example.com/about, it will be re-written as http://example.com/index.php?page=about.

I’d also suggest doing some validation on $_GET['page'] in your index.php script too, as people will be able to navigation your file system otherwise.

Upvotes: 1

AndVla
AndVla

Reputation: 713

This is what you need

RewriteEngine On
RewriteRule ^([a-z]+)$ index.php?&page=$1 [QSA]

Upvotes: 0

Mrinmoy Ghoshal
Mrinmoy Ghoshal

Reputation: 2834

Your First Line Should Be:

RewriteEngine On

Then Use

RewriteCond %{REQUEST_FILENAME} !-f

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

Instead of

RewriteRule ^(.+)$ index.php?&page=$1 [NC]

Upvotes: 0

Niclas Larsson
Niclas Larsson

Reputation: 1317

# This line starts the mod_rewrite module
RewriteEngine on

# If the request is for a file that already exists on the server
RewriteCond %{REQUEST_FILENAME} !-f

# Pass all trafic through the index file (if the requested file doesn't exist)
RewriteRule ^(.*)$ index.php?$1 [L,QSA]

/project/1 will be the same as $_GET['project'] = 1

Upvotes: 0

Related Questions