PHP: serve pages without .php files in file structure

I am working on creating an internal CMS for clients. Instead of creating a new php file for each page, I wonder if there is a way to load the page based on the URL, but not the physical php file in this place.

So, if I visit the site www.mysite.com/new-page, I would like it to be just a link to my template, content, etc., and not to the real .php file.

Sorry if I didn’t explain it correctly, but it’s hard for me to explain it.

Thanks.

+3
source share
3 answers

It looks like you need a front controller template .

Basically, each URL is redirected to a single PHP page, which determines what to do with it. You can use Apache mod_rewrite to do this with this .htaccess:

RewriteEngine on RewriteBase / RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$ index.php 

This redirects everything except the static content files to index.php. Adjust as needed.

If you just want to influence the URL / new page, try something like:

 RewriteEngine on RewriteBase / RewriteRule ^new-page/ myhandler.php 

Any URLs starting with the “new page” will be sent to myhandler.php.

+4
source

This is usually a web server that handles this for you in conjunction with your PHP code. So, for example, if you used Apache, you could use mod_rewrite to do something like:

 RewriteEngine on RewriteRule ^page/([^/\.]+)/?$ index.php?page=$1 [L] 

And then in your php code you can check $_GET['page'] to see which page is being called.

So a visit to mysite.com/page/blah really get access to index.php?page=blah .

+4
source

Using mod_rewrite to rewrite URLs on one of the PHP pages is a solution. I would prefer to use a more general rewrite rule that rewrites any URLs that are not related to a directory file existing on the server.

 # Rewrite URLs of the form 'x' to the form 'index.php?q=x'. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !=/favicon.ico RewriteRule ^(.*)$ index.php?q=$1 [L,QSA] 
+1
source

All Articles