rewrite pretty urls with php and htaccess, mapping 404 for subpages - php

In .htaccess I have following rules for having page/subpage rewrite.
#Permalinks
RewriteEngine on
<IfModule mod_rewrite.c>
RewriteEngine On
#catch potential subpages first
RewriteRule ^([a-z\-]+)/([a-z\-]+)/?$ index.php?page=$1&subpage=$2 [L]
#
RewriteRule ^([a-z\-]+)$ index.php?page=$1 [L]
</IfModule>
In php I do this:
if (!$_GET) {
//
$page = "home";
$page_title = "General Site Title";
include ("template/index.php");
//
} else if ($_GET['page'] == "words") {
//
$page = "words";
$page_title = "Words Page";
include ("template/words.php");
//
} else if ($_GET['page'] == "about") {
//
$page = "about";
$page_title = "About Page";
include ("template/about.php");
//
} else {
//
header("HTTP/1.0 404 Not Found");
//
include ("template/404.php");
//
exit();
//
}
This works great, for showing 404.php when page doesn't exist.
But what if I want to have 404.php also when page/subpage doesn't exist?
For example I'm planning to have /members page. If someone goes to non existing /members/user1, I need to check DB for existing user, if doesn't exist I should show 404.php but is this correct logic to use in this situation?
p.s. how do I add rewrite /about/ to show same page? currently /about returns 200, but /about/ returns apache page not found.

First of correction in rules to make trailing slash optional in both rules:
RewriteEngine On
RewriteRule ^([a-z-]+)/([a-z-]+)/?$ index.php?page=$1&subpage=$2 [L,NC,QSA]
RewriteRule ^([a-z-]+)/?$ index.php?page=$1 [L,NC,QSA]
Now about checking /members/user1 yes you can check DB for existence of member record and if not found you can return 404 status/page.

Related

How to fix .htaccess rewrite not showing CSS [duplicate]

This question already has answers here:
Seo Friendly URL results in CSS IMG and JS not working
(2 answers)
Closed 3 years ago.
I'm running a localhost on my Mac using the native sites, and I can't seem to get .htaccess CSS working. I'm using an index.php page, that is then given url variables to tell which page to display (ex. index.php?login). There two issues I'm facing here: The first is that it redirects to a page where my global styles aren't included, and the second is that it shows the homepage instead of my login page.
I've tried navigating to the rewritten site as localhost/index.php?login, and all the CSS and HTML displays fine. It's only when I rewrite it as localhost/login that it fails. It shows my homepage without any of the styles that should be include from index.php
Here is my .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
DirectoryIndex index.php
RewriteRule ^login$ index.php?login [NC]
</IfModule>
Here is my index.php
//Check for more GET variables.
$url = $_SERVER['REQUEST_URI'];
$split = explode("?", $url);
if (isset($split[1])) {
$newvarsarray = explode("&", $split[1]);
foreach ($newvarsarray as $newvar) {
$keyandvalue = explode("=", $newvar);
if (isset($keyandvalue[1])) {
$_GET[$keyandvalue[0]] = $keyandvalue[1];
} else {
$_GET[$keyandvalue[0]] = '';
}
}
} else {
//No additional vars, leave $_GET alone.
}
include_once 'globalheader.html';//Imports styles and things
include_once 'header.html';//Stylized header
//This is the area where we handle the different states of the webpage and import them into here
if (empty($_GET)) {
//Main homepage
include_once 'mainpage.html';
} else if (isset($_GET['login'])) {
//Login page
include_once 'login.html';
} else if (isset($_GET['register'])) {
//Register page
include_once 'register.html';
} else if (isset($_GET['profile'])) {
//Profile page
}
include_once 'footer.html';//Stylized footer
include_once 'globalfooter.html';//Closes things from globalheader.html
?>
I want it to display the correct page with correct CSS instead of seemingly skipping over the entirety of index.php and just using the .html file.
tl;dr you are missing [OR].
A file cannot be "not a file nor a directory" at the same time.
DirectoryIndex index.php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^login$ index.php?login [NC]
</IfModule>

htaccess hide file name from url

I need to hide the profile.php from appearing in the URL.
So here's what I have:
The URL I am accessing:
sampleuser.domain.com/profile.php
How I get the user 'sampleuser':
$url = "//".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
/*this will give me $url = '//sampleuser.domain.com/profile.php'; */
function get_user_from_url($url)
{
if (strpos($url , 'www.') !== false) {
preg_match('/\/\/www.(.*?)\.domain/', $url, $val);
}
else
{
preg_match('/\/\/(.*?)\./', $url, $val);
}
return $val[1];
}
$user = get_user_from_url($url);
echo $user;
I just need to hide the profile.php, also the thing to consider is if we hide the profile.php, it might conflict with the index.php.
But luckily we will only access the index.php if the URL is only domain.com (without user).
I'm low on htaccess knowledge, can anyone give me the direct answer, and I would be very appreciative if you can add some explanation, it'll give me a head start on learning htaccess.
So basically, what I was making is a dynamic subdomain. So I added a subdomain on my DNS:
*.domain.com
then added these on my htaccess
<IfModule mod_rewrite.c>
#Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !www.domain.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-]+).domain.com [NC]
RewriteRule ^/?$ /agent/index.php?user=%2 [L]
</IfModule>

Do not get mod_rewrite working with $_GET['page']

My current link is:
domain.com/folder/index.php?page=home
and i try to get it to this:
domain.com/folder/home
The PHP code that I use to get the page
<?php
if (isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = 'home';
}
if (strpos($page, '/') !== false || !file_exists("pages/$page.php")) {
$page = 'error';
}
include ("pages/$page.php");
?>
I tryed a lot to get the right .htaccess code to rewrite my URL, from generators to forum posts but I can not get the right code.
I hope someone can get me in the right direction to get this working.
these .htaccess rules should help you get started
RewriteEngine On
RewriteBase /
#### this allows you to write your links in the form /folder/home ####
RewriteRule ^folder/([0-9]+)$ folder/index.php?page=$1 [NC,L]
#### to dynamically redirect to /folder/home ####
RewriteCond %{THE_REQUEST} /(?:index\.php)?\?page=([^&\s]+) [NC]
RewriteRule ^ %1? [R=302,L,NE]
Redirect ^(.*).php$ index.php?page=$1 [L,QSA]
utilize this in your htaccess

Simple PHP Modules .htaccess

I have starting creating a simple module system to help me build and visualise how all the pages of my application are going to be organised behind the scenes.
I'm starting to feel this isn't a very good way of achieving this as I will end up with a huge .htaccess file to rewrite all urls for each module.
RewriteEngine On
RewriteRule ^login$ index.php?page=login
Each module should have it's own controller, so that it is seperate from other module code, and any page inside any module should be able to access configuration array values from within the root index.php file.
<?php
if(isset($_GET['page'])) {
switch($_GET['page']) {
case 'login':
$page = 'modules/default/login.php';
break;
}
} else {
$page = 'modules/default/homepage.php';
}
include($page);
?>
I'm having issues as to what will happen when I add an account module that contains other pages. e.g. /account or /account/profile
<?php
if(isset($_GET['page'])) {
switch($_GET['page']) {
case 'settings':
$page = 'modules/account/settings/index.php';
break;
}
} else {
$page = 'modules/account/index.php';
}
include($page);
?>
Is there a better way this can be done?
Hopefully you can see what I'm trying to do.
Better to have your rule to catch all URIs that are not files or directories like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1 [L,QSA]
Then use $_GET['page'] parameter to get all the URI values in your PHP code.

PHP: htaccess default variable

I want to set a default variable for a query that comes at the end of a url
The .htaccess file redirects the url as follows:
http://www.server.com/folder/subfolder/index.php?page="some-page-name"
displayed url
http://www.server.com/folder/some-page-name
if the page name is not set, as in:
http://www.server.com/folder/
the default would be "index". I could use php function header("location:url") but that would display the "index" part at the end if the url... that I don't want.
htacess content
Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine On
#RewriteCond %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteBase /folder/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^.*\.css.*$ [NC]
RewriteRule ^(.*)$ subfolder/index.php/?page=$1 [L]
</IfModule>
<IfModule mod_rewrite.c>
ErrorDocument 404 /error.html
ErrorDocument 403 /error.html
</IfModule>
You don't have to redirect to index.php. You can use something like:
header('Location: /folder/front-page');
If you just want http://example.com/folder/ show up your index page, you could use the following in your PHP script:
$requested_page = filter_input(INPUT_GET, 'pageID');
$allowed_pages = array('some-page', 'some-page-name');
if($requested_page == ''){
// display your index page as ?pageID is not set or empty
}
elseif(in_array($requested_page, $allowed_pages)){
// display $requested_page
}
else{
// display a 404 Not Found error
}
Try this code in your PHP file:
$pageID = 'index';
if(isset($_REQUEST['pageID']) && !empty($_REQUEST['pageID']))
$pageID = get_magic_quotes_gpc() ? stripslashes($_REQUEST['pageID']) : $_REQUEST['pageID'];
// Your code should now use the $pageID variable...
What this will do is set $pageID to a default value of "index". Then, if a different PageID is given by the mod_rewrite, $pageID will bet set to that value. Your code should then use the value of $pageID.
Your question was too long, didn't read, however if you just want to set a variable in your .htaccess file and pass it to PHP it's pretty easy to do it like this -
In the .htaccess file (http://httpd.apache.org/docs/2.0/mod/mod_env.html#setenv):
SetEnv default_url http://my.url/goes/here
In your PHP script (http://www.php.net/manual/en/reserved.variables.environment.php):
header('Location: '. $_ENV['default_url']);
Alternately, if you have ErrorDocument handlers, you might be able to simply send a status code as well (see the third option to header(), http://us.php.net/manual/en/function.header.php).

Categories