I have been smashing my head against wall for whole day but could not understand how can I make my URL show the page title in URL instead of all query parameters.
I just simply wants to convert my this URL
http://www.def.com/post.php?id=1
to
http://www.def.com/my-page-title.html
I read many articles and specially questions on SO but non of them were really answering this. I do not have enough reputations to put other similar links here.
I just want to get the title of my page and show it in my URL.
A fairly standard .htaccess that will route all paths where a directory or file are not found at the path:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^route-page\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /route-page.php [L]
</IfModule>
Thereafter, you have to have the /route-page.php (whatever you name it) read the URI: $_SERVER['REQUEST_URI'], parse "/my-page-title.html" and figure out how to load the correct page from there.
route-page.php
<?php
$path = $_SERVER['REQUEST_URI'];
//query for row of data with that path...
//output results
Because your actual page name may have symbols in it, it's best if you have the expected path "my-page-title.html" in an indexed column of your database. This way, you can quickly grab the page based on the path. Also, since all unfound URLs are going to this page, you need to handle 404 errors manually (i.e. if you don't find a page that matches the path specified, output a 404 error):
if( $pageNotFound ) {
header("HTTP/1.0 404 Not Found");
echo("<h1>Page Not Found</h1>");
}
Related
In Node we can get an url address with a structure like this /example/:page/:id and we can take the page and id params. Is there a possibility to do something similar using PHP? Or is it only possible using the "?" with all the wanted params after the interrogation point?
I searched for a while and I tried some configurations in the htaccess file. All of them gave some kind of error like 403, 404 or in one of the configurations the intentioned page was loaded but it didn't find the css, js and images files.
Thanks
Edit:
I will put the solution I found here because maybe it can be useful for someone someday. After looking for some routers packages, I saw them instructing to put these lines in the htaccess file:
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]
I've tried something like this before and it was the one that I mentioned in the question that loaded the page but it didn't find the files like css, js, etc.
So I've decide to check the base url and I saw this was the point where the error was coming. After I changed it, the page loaded as the expected and now it's possible to get the value where the users can put a number and redirect to the page that they want (it's something like a magazine).
You can achieve it many ways.
In Laravel (see Documentation). I think every framework now has routing implemented.
Route::get('example/{page}/{id}', function ($page, $id) {
//
})->where(['page' => '[0-9]+', 'id' => '[a-z]+']);
With Mod-rewrite and then with access through $_GET parameters.
RewriteEngine on
RewriteRule ^example/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ index.php?page=$1&id=$2 [NC]
You can also redirect everything to index.php and there implement your own router. See: Redirect all to index.php using htaccess
RewriteEngine on
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
Something like this could work
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode( '/', $uri );
// all of our endpoints start with /person
// everything else results in a 404 Not Found
if ($uri[1] !== 'page') {
header("HTTP/1.1 404 Not Found");
exit();
}
For more reference visit this url
https://developer.okta.com/blog/2019/03/08/simple-rest-api-php
have you tried parse_url()?
it will return and associative array which has all the components in your URL
I want to know how to page url without .php extension
for ex here is my website :
http://mywebsite.com/ now from the home page whenever i click on any gallery it will goes to the page gallery.php with querystring of galleryID for ex
http://mywebsite.com/gallery.php?id=29
So instead of this gallery.php?id=29 I want to make the url something related to the page title
http://mywebsite.com/9-WEDDING-GIFT-IDEAS
Thanks in advance
I'd recommend using a PHP framework once you start going down this path, that gives your application/site a structure, and the ability to setup routes (paths) like you're requesting.
I'm a fan of Laravel, this allows you to use http://example.com/index.php/friendly-url/goes-here if you haven't setup Apache (the web server) to remove them.
You can remove the index.php/ part and just have http://example.com/friendly-url/goes-here by using the Apache mod_rewrite which Laravel includes for you. Check out the documentation under Pretty URLs
Hope that helps.
There are two ways you can do this. If you don't have a ton of URLs, you can add them in to your '.htaccess' file manually.
RewriteEngine On
# MANUAL
RewriteRule ^9-WEDDING-GIFT-IDEAS/?$ gallery.php?id=29 [L]
RewriteRule ^MOST-BEAUTIFUL-WEDDING-LOCATIONS/?$ gallery.php?id=30 [L]
# ...
Otherwise, you can have 'gallery.php' handle looking up which article to display based on the title. So if it receives a title of '9-WEDDING-GIFT-IDEAS', then it can look up that title in the database and fetch the article for that title. Here, the article title will be passed as the 'id' parameter to 'gallery.php'.
RewriteEngine On
# PARSING HANDLED IN gallery.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ gallery.php?id=$1 [L]
EDIT:
<?php
// gallery.php
$article_title = $_GET['id'];
// ...
// DO A DB LOOKUP TO GET THE ARTICLE ID WHERE TITLE = '$article_title'
// OR JUST GET THE ARTICLE BASED ON THE TITLE INSTEAD
In my domain example.com , I want to put all page files in a directory at root for example named file. So for example I put about.php the file directory and want to let users to access this page with this URL : example.com/about
or for example put user directory in the file directory and put login.php in it , and want to let users to access it with : example.com/user/login
In fact I want to remove .php and the file from the URLs.
AND
If those files don't exist , it should load a default file like index.php at root. for example the URL example.com/blabla should be mapped to the index.php
In fact , I want to make two conditions in mod rewrite with the mentioned priority.
notice : of course I should be able to use variables like $_GET at files like about.php
UPDATE : in summary , it should work with this logic :
if the URI isn't a file or directory{
if file/URI.php is a file
load file/URI.php
else
load index.php
}
some body gave an answer to use ErrorDocument 404 index.php , but it's a really bad idea (and now has deleted his answer !)
Thanks for your help...
A conditional rewrite (if the pages exist) sounds like a bad and complicated idea, if it even is possible.
I would rewrite everything to /index.php and control everything from there:
If the components of the url lead to an existing page, use / include that content;
If no valid page is found, present your original index content.
Example redirect rules for your situation:
RewriteEngine on
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^.*$ /index.php?id=$1 [QSA,L]
Will include the requested path in id and append the variables from the original query string (the QSA flag).
More specific for your /user/login example would be:
RewriteRule ^([\w-]+)/([\w-]+)$ /index.php?path=$1&file=$2 [QSA,L]
[\w-+] : any word character (including _) and the -
I am new to .htacces and for ages I have been trying to get my domain from:
www.domain.com/post.php?post_id=20
to something such as this:
www.domain.com/post/this-is-the-title/
As I said I am new to .htaccess but anything would help please!
NOTE: I would be getting the titles of my blog posts from an SQL database somehow
If the page titles are database-driven (or otherwise dynamic), I don't see how you could get away with .htaccess rewrites. It would make more sense to use routing in your PHP script.
I have written about an extremely simple routing method here. It's for people only getting into the subject, but you should be able to build a database-driven router based on that.
Essentially, route all your traffic through index.php and there, get the request URI and decide what resources to load.
[EDIT]
Let me elaborate a bit, using the info from my blog post.
Assuming you have your site set up and running, first direct the traffic to index.php. You do that in .htaccess and it can be done like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
Then, in index.php (or in a script that's called from index.php), you can get the request URI:
$uri = $_SERVER["REQUEST_URI"];
OK, so far so good. Now let's assume your database holds page content along with the page aliases. The uri will most probably be the page alias, so all you need to do is something like this:
$pdo = new PDO(/* your db connection params */);
$page = $pdo
->query("SELECT * FROM pages WHERE alias = :alias",
array("alias" => $uri)
)
->fetch();
At this point you should have the page content corresponding to the title (or alias) in the URI string. All you need to do now is display it any way you want:
echo $page["content"];
You can't. You have to put the title on the query string.
An .htaccess cannot safely get anything from the database.
Since you are going to rewrite the url, why not simply write the post title in the URI?
You can't do this with an .htaccess cause you need to get "the titles of your blog posts from an SQL database somehow", do a redirect with PHP. :)
I am working on creating page links from DB like the following example.
Current page:
www.example.com/page.php?pid=7
In the DB it is saved as title "contact-us" under category "Company Info"
I want it to be like:
www.example.com/company-info/contact-us.html
I have tried different solution and answers but did not got any luck. I am not sure, where will be the PHP part and which rules to write for .htaccess files.
In apache (or .hataccess) do something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /proxy.php?_url=$1 [QSA,L]
So in a nutshell, if the resource being requested doens't exist, redirect it to a proxy.php file. From there $_REQUEST['_url'] will be the url the user was requesting.
Then create proxy.php in your home directory and add whatever logic you'd like to load the correct content.
If you use this from .htaccess, then you may need to add RewriteBase / to your config.
If you want to find this page by url, you will probably do this through php and .htaccess. Make a .htaccess that calls page.php for each and every request. You don't need the pid=7, because, well, how should the .htaccess know it is 7, right? :)
In page.php, you take the original url and split it on the slashes, so you get the category (company-info) and the page itself (contact-us.html). Then, you can look these up in the database. This is in a nutshell how many software works, including Wikipedia (MediaWiki) and CodeIgnitor.
Mind that 'company-info' isn't the same as 'Company Info'. You'll have to specify the url-version in the database to be able to use it for look-up.