简体   繁体   中英

Redirect all requests to single page

I have a food blog website, with many posts stored in a database. When someone clicks on a link to a post, the website searches the database for the post and presents it in a template. I don't store an HTML file for each post.

Right now, I do it by handling a 404 error (which goes off because the requested HTML file doesn't exist) and searching the database from there. I know this isn't right.

How can I set up my web server (Apache running on a Raspberry Pi), so that all requests go to one page, which will do the searching and send the user to the right page? And is this the right thing to do?

You can do that with a file you put in your website root named .htaccess and using the mod_rewrite module. You'll need to make sure .htaccess and mod_rewrite are enabled in the Apache configuration. But once enabled you can do something like this:

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

That will rewrite any URL that doesn't refer to an actual existing file or directory to your index.php which you can use to handle the request.

For example, if someone visits http://yourdomain.com/article , the path will be internally rewritten to index.php?path=article and you can access the path using $_GET['path'] .

Note: If you want to literally serve everything through that single entry point you could remove the two middle lines and that would send everything through there. Including images, scripts, CSS etc, which is generally not what you want.

You need proper .htaccess rules in your public root directory and you need a apache2 mod_rewrite module enabled.

On Ubuntu you can can enable it with the following command:

sudo a2enmod rewrite

your .htaccess file could look like the following:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

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