I would like to make the URLs of my Store URL-friendly.
Current URL Structure
https://my-domain.com/store/store.php?page=packages&id=1
Desired URL Structure
https://my-domain.com/store/packages/1
And also for direct access to the PHP files such as:
https://my-domain.com/store/profile.php to https://my-domain.com/store/profile
How would I need to go after this? I really appreciate any help you can provide.
Also might be note worthy that in the base directory a WordPress site is running with its own .htaccess file.
I already tried it with this
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^store/store/page/(.*)/id/(.*) /store/store.php?page=$1&id=$2
RewriteRule ^store/store/page/(.*)/id/(.*)/ /store/store.php?page=$1&id=$2
But that didn't work
This code will work.
RewriteEngine will remove .php from all PHP Files
RewriteRule will rewrite url like page/id
For Removing .php extension
RewriteEngine On
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]
For page/id
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)? store.php?page=$1&id=$2 [L]
</IfModule>
You can use this for the first part:
RewriteRule ^store/((?!store)[^/]+)/([^/]+)$ /store/store.php?page=$1&id=$2 [L]
Although nothing is wrong with anyone else's answers, the more modern way to do this (including WordPress, Symfony and Laravel) is to send non-existent URLs to a single router script. By doing this, you only have to mess with an htaccess file once to set things up, and never touch it again if you add more "sub-folders", you can do all of that in just PHP. This is also more portable which means you can bring it to other server platforms such as Nginx with little changes, and don't need to deal with RegEx.
The htaccess is fairly straightforward. Route all requests that start with /store/ and don't exist as a file (such as images, JS and CSS) or directory to a single new file called router.php in your /store/ folder. This is an internal redirect, which means it isn't a 301 or 302.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^store/ /store/router.php [L]
Then in your new router.php file you can parse $_SERVER['REQUEST_URI'] to determine the URL that was actually requested, and you can even rebuild the global $_GET variable:
// Parse the originally requested URL into parts
$requestUrlParts = parse_url($_SERVER['REQUEST_URI']);
// Parse the query string into parts, erase the old global _GET array
parse_str($requestUrlParts['query'], $_GET);
// Handle
switch($requestUrlParts['path']){
case '/store/store.php';
include '/store/store.php';
exit;
// Custom 404 logic here
default:
http_response_code(404);
echo 'The page you are looking for cannot be found';
exit;
}
I'd also recommend putting the htaccess rule into the site root's htaccess folder, above WordPress's. There's nothing wrong with creating multiple files, this just keeps things in a central place and makes it easier (IMHO) to debug.
Related
I'm trying to rewrite all requests to index.php and then there decide which file to include depending on the value in the $_GET['p'] variable. For example I have a script called update.php in the home directory of my site called leltar, which I would like to be included if the opened page is localhost/leltar/update.
However, the problem is that the rewriting does not work because WAMP runs the script even though the .php extension is not in the link. The output is just the one from the script, nothing is shown from index.php. How can I stop WAMP from running the script with similar name? I suppose, there is something wrong with my .htaccess code as well because if I open pages other than localhost/leltar/update, the value of $_GET['p'] is the string "index.php" all the time.
.htaccess file:
RewriteEngine On
RewriteRule ^(.*)$ index.php?p=$1
index.php:
// ...
switch ($_GET['p']) {
case 'update':
require_once('update.php');
break;
default:
// something else
break;
}
// ...
The content of update.php is not relevant.
EDIT:
The main problem is that by default or even when I use the RewriteCond %{REQUEST_FILENAME} !-f rewrite condition if there is a file with the same name as the user-friendly end of the link, WAMP somehow overrides my rewrite rules. If I put a picture named pic.jpg into the www folder and open localhost/pic.jpg, the image shows up, obviously. However, if I leave out the extension visiting the page localhost/pic, I get the same output as well (instead of getting a 404 Not Found error because of the non-exisiting folder, I suppose).
EDIT 2:
On a real server there isn't any problem. If I leave out the extension a 404 error is thrown, so it's definitely a WAMP-specific thing.
Rules in .htaccess files effectively loop until the URL does not change (because the processing is restarted each time, which means the rules are also processed again) so of course your rule loops until p is equal to itself.
You don't actually need p, you can just check $_SERVER['REQUEST_URI'] in your PHP script and that will tell you the original requested URI (not the same as REQUEST_URI below, which does change with each rewrite).
So just use this:
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule ^ index.php [L]
But... you probably want files that exist to be served, such as images, scripts etc. so the usual thing is to do this and check if the file exists:
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Although it's more efficient to do this and list the directories with files in them that you want to be served:
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_URI} !^/(?:images|css|scripts)/
RewriteRule ^ index.php [L]
Just change the list to the names of the directories that have your static files in.
Update
From the comments, it seems you have another rewrite that is adding .php to URLs, so they can work without it. In order to not rewrite them to index.php, I suggest putting the rewrite before this one. Otherwise, you can check if the URL exists with .php on the end of it like this. Perhaps combining it with the folder check rather than having two file-system checks.
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_FILENAME}.php !-f
RewriteCond %{REQUEST_URI} !^/(?:images|css|scripts)/
RewriteRule ^ index.php [L]
You can add specific file exceptions to the third rule like this:
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_URI} !^/(?:images|css|scripts)/
RewriteCond %{REQUEST_URI} !=/some/url.php
RewriteCond %{REQUEST_URI} !=/some_other_url.php
RewriteRule ^ index.php [L]
Indeed, as #SuperDuperApps assumed, the problem was that WAMP has MultiViews enabled by default. Adding Options -MultiViews to my .htaccess file solved all my problems, my initial code mentioned in the question works fine now.
I have a site that I'm working on, but I'm annoyed that I have to work with ugly URLS. So, I have a URL of http://example.com/user.php?id=54 and another of http://example.com/foobar.php?name=Test.
How could I convert both of them to pretty URLS without adding it to .htaccess for every URL I want to make pretty?
example.com/user.php?id=54 => example.com/user/54
example.com/foobar.php?name=Test => example.com/foobar/Test
I have this in my .htaccess file:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^([^/]+)/?$ $1.php [L]
RewriteRule ^$1/$3/? /$1.php?$2=$3 [NC]
Thanks,
Lucy
My full .htaccess file:
# include classes on every page
php_value auto_prepend_file Resources/Classes.php
# add custom Directory Indexes
DirectoryIndex index.php Default.php Down.php
# begin routing to pretty URLs
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^/(?!Resources)([0-9a-zA-Z-]+)/([0-9]+) /$1.php?id=$2 [NC]
RewriteRule ^/(?!Resources)([0-9a-zA-Z-]+)/([a-zA-Z-]+) /$1.php?name=$2 [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
Try this
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^user/([0-9]+) /user.php?id=$1 [QSA,L]
RewriteRule ^foobar/([0-9a-zA-Z-]+) /foobar.php?name=$1 [QSA,L]
if you want global rule you can make
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9a-zA-Z-]+)/([0-9a-zA-Z-]+) /$1.php?parameter=$2 [NC]
or more specifically
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9a-zA-Z-]+)/([0-9]+) /$1.php?id=$2 [NC]
RewriteRule ^([0-9a-zA-Z-]+)/([a-zA-Z-]+) /$1.php?name=$2 [NC]
when argument will be a string it will pas name parameter and when argument will be integer there will be id parameter passed.
I may delete this answer in the future as it might be specific to my setup.
I recently discovered, using Apache, that anything after the URL was populating the PATH_INFO environment variable. This means that given your example, example.com/user/54, if user was a script the server could process, anything after it would be populated into PATH_INFO; in this case it would look like /54. This is a great find because with proper structure, you could make your own router similar to Rails.
I would create some landing page (e.g., index) which is going to be your application router: example.com/index/<model>/<id>/. Inside index would be your routing code. I'll use Perl to demonstrate, since it's better than PHP :) Note that index could be called anything that Apache can process (e.g., router.php, index.pl, application.rb); though, removing the extension adds to the beauty of the URL.
index:
#!/usr/bin/perl
use 5.012;
# Retrieve what you're looking for; obviously not production-ready
my ($model,$id) = $ENV{PATH_INFO} =~ m{^/([^/]+?)/([^/]+)};
# route the request
given($model){
when('user'){ callUser($id); } # callUser defined elsewhere, perhaps another script
when('foobar'){ callFoobar($id); } # callFoobar defined elsewher, perhaps another script
default { makePageDefault(); }
}
http://example.com/index/user/1: passes 1 to callUser()
http://example.com/index/foobar/5: passes 5 to callFoodbar()
http://example.com/index/user: calls makePageDefault() because regex was not smart enough to handle anything without an ID
http://example.com/index/diffmodel/1: also calls makePageDefault(), since we don't handle diffmodel didn't exist
The script above is not production ready because it doesn't perform any sanitation and doesn't handle all the use cases you will need. My guess is you want something similar to Rails (e.g., example.com/movie/1/edit). While Apache is designed to handle the routing for you, there is some convenience in being able to manage this close to where your application code lives.
I have not implemented this method, so I'm curious to hear if this is something used and if there's any reason not to trust it.
I'm working on a website that has been built sloppily.
The website is filled with regular links that are translated into the corresponding .php pages by the .htaccess page.
This is it:
RewriteEngine on
RewriteRule ^koral/(.*)/$ page.php?name=$1
RewriteRule ^koral/(.*)$ page.php?name=$1
RewriteRule ^(.*).html/(.*)/(.*)/(.*)$ cat.php?cat=$1&page=$2&order=$3&dir=$4
RewriteRule ^(.*).html$ cat.php?cat=$1
RewriteRule ^(.*)/(.*).html$ product.php?cat=$1&product=$2
<IfModule mod_security.c>
SecFilterEngine Off
</IfModule>
First of all, I would love some help regarding whether or not this page has everything it should. I've never messed with it before.
Secondly and my main issue, if, for example, I would write the address www.thewebsite.com/foobar.html, it would be translated into www.thewebsite.com/cat.php?cat=foobar by the .htaccess page, and it would give a database error (and reveal information about the database).
I've put a check into cat.php which checks if the category exists, but I can't redirect the user to the 404 error page. There's a page called 404.shtml in the website, but redirecting the user to it causes the .htaccess to just change it again to cat.php?cat=404.
Is the way they used the .htaccess page normal? Should I change this system?
And how are users sent to error pages? From what I understood the server should be doing it on its own?
I would love some clarification... There is some much about this subject I don't understand.
Update:
This is my new .htaccess page
RewriteEngine on
RewriteRule ^error.php?err=(.*)$ Error$1.html
# Only apply this rule if we're not requesting a file...
RewriteCond %{REQUEST_FILENAME} !-f [NC]
# ...and if we're not requesting a directory.
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteRule ^koral/(.*)/$ page.php?name=$1
RewriteRule ^koral/(.*)$ page.php?name=$1
RewriteRule ^(.*).html/(.*)/(.*)/(.*)$ cat.php?cat=$1&page=$2&order=$3&dir=$4
RewriteRule ^(.*).html$ cat.php?cat=$1
RewriteRule ^(.*)/(.*).html$ product.php?cat=$1&product=$2
<IfModule mod_security.c>
SecFilterEngine Off
</IfModule>
Because the redirecting is in the code and the user cannot see it, I allowed myself to write the link in a non-clean way. I tried turning it into a clean URL but the following does not do anything:
RewriteRule ^error.php?err=(.*)$ Error$1.html
Can someone please help me understand why? I thought since error.php is a real page, I should put it before the conditional but it didn't work. BTW, I saw in an article about .htaccess that the page should start with Options +FollowSymLinks. It seems to me that everyone sort of has their own way of writing it. Is there a guide or something like that, which I can be sure is authentic and covers all the bases there is about .htaccess?
Thank you so much!!
Using rewrite rules to work around links to .html pages that don't exist is unusual in my experience, but it's really just a different take on "pretty" URLs, e.g. www.thewebsite.com/foobar/ gets routed to cat.php?cat=foobar on the backend.
Your 404 issue is different. You need to be able to display error pages.
One option here is to rewrite requests as long as they don't request an existing file. This is very common for serving up static content like images, CSS files, and the like. To do this, you can use the -d and -f options to RewriteCond, which apply when requesting a directory and file respectively:
RewriteEngine On
# Only apply this rule if we're not requesting a file...
RewriteCond %{REQUEST_FILENAME} !-f [NC]
# ...and if we're not requesting a directory.
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteRule ^([^.]+)\.html$ cat.php?cat=$1 [L,QSA]
Now, requests to 404.shtml should go through, because you're requesting an existing file on the filesystem.
Note that the RewriteConds only apply to the single RewriteRule that immediately follows. For additional RewriteRules, also include additional RewriteConds.
Your regex is wrong anywhere. Literal dot needs to be escaped using otherwise it will match any character. Also it is better to use L and QSA flags to end each rule properly.
RewriteEngine on
RewriteBase /
RewriteRule ^koral/([^/]+)/?$ page.php?name=$1 [L,QSA]
RewriteRule ^([^.]+)\.html/([^/]+)/([^/]+)/([^/]*)/?$ cat.php?cat=$1&page=$2&order=$3&dir=$4 [L,QSA]
RewriteRule ^([^.]+)\.html$ cat.php?cat=$1 [L,QSA]
RewriteRule ^([^/]+)/([^.]+)\.html$ product.php?cat=$1&product=$2 [L,QSA]
I have re-written my URL from website.com?id=1 to website.com/1 and I'm getting 404 errors when trying to access the page and cannot think of a solution to this. I'm currently developing a link shortener. This is required so users will be able to access their shorted links.
This is my current .htaccessfile
RewriteEngine On
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /(index\.php)?\?id=([0-9]+)([^\ ]*)
RewriteRule ^ /%3?%4 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)/?$ /?id=$1 [L,QSA]
I cannot figure out whether this has something to do with the .htaccess file or if I need to add something else to my php code.
Would someone have some sort of idea? Thanks.
You need to explicitly rewrite back to index.php in your second rule. By the time rewrite rules are processed the DirectoryIndex directive has already been processed (or may never be processed at all - it depends a little on your virtual host configuration and in what scope the DirectoryIndex directive was declared).
The end result of this is that you need to explicitly rewrite the request to the script that you want to handle the request, you can't just rewrite it to the root of a directory. Try changing your second rewrite rule to:
RewriteRule ^([0-9]+)/?$ /index.php?id=$1 [L,QSA]
On a personal note, it's interesting to see someone else use the %{THE_REQUEST} approach to this problem, this is an idea that I myself only recently came up with, although presumably I am not the first to do so. For the benefit of future visitors, here is a related post that explains why this requirement would come about and the thinking behind it.
I think you have written wrong rewrite rules.
They must be something like this:
for example.com/website.php?id=x..
RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=([^/]+)$
RewriteRule ^website\.php$ %1/ [L]
as discussed here: https://stackoverflow.com/a/4951918/2274209
Hope this will solve your query.
I am trying to get url from:
192.168.0.1/movie-page.php?id=123
to:
192.168.0.1/movie/movie-name
or even (for now):
192.168.0.1/movie/123
I've simplified it by using this url (to get something working):
192.168.0.1/pet_care_info_07_07_2008.php TO 192.168.0.1/pet-care/
my .htaccess file:
RewriteEngine On
RewriteRule ^pet-care/?$ pet_care_info_07_07_2008.php [NC,L]
What am I doing wrong? I've tried many combinations but no luck and my patience is running out...
I am running this on my local NAS which should have mod_rewrite enabled by default. I have tested .htaccess by entering random string in .htaccess file and opening the page, I got 404 error. I assume this means that .htaccess is being used since the page stops functioning if the file is malformed.
If you want to rewrite:
192.168.0.1/movie-page.php?id=123 too
192.168.0.1/movie/movie-name or 192.168.0.1/movie/123
Then you would do something like, but will require you manually add a rewrite for any new route (fancy url) you want, and eventually you may want your script to create routes dynamically or have a single entry point to sanitize:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^movie/([a-zA-Z0-9-]+)$ movie-page.php?id=$1 [L]
So a better method is to route everything through the rewrite:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
Then handle the route by splitting the $_GET['route'] with explode()
<?php
//192.168.0.1/movie/movie-name
$route = (isset($_GET['route'])?explode('/',$_GET['route']):null);
if(!empty($route)){
//example
$route[0]; //movie
$route[1]; //movie-name
}
?>
You want something like this:
RewriteRule ^movie/([0-9]*)$ /movie-page.php?id=$1 [L,R=301]
That will give the movie ID version with a numeric ID.