Dynamic Website while still being SEO compatible [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.htacces to create friendly URLs. Help needed
I would like to have create a website, which loads up content from a MySQL database via PHP, while still being optimized for search engines.
I have considered a few approaches and was looking for some advice on which way would the best.
Users on my website would fill out a form and submit it, which gets saved in the SQL database. I would like to have it so that each new page could be accessed like this:
domain.com/plugins/whatever
domain.com/plugins/anotherpagename
Some approaches:
1.
A script generates a static HTML page in the plugins folder when the form is submitted. When the page is edited (there will be a edit button), the HTML page gets overwritten with the updated information.
domain.com/plugins/whatever and domain.com/plugins/anotherpagename would all redirect to a PHP script.
However, I do not know how to create a .htaccess which would allow the PHP script to get the page name so that it can search the SQL database and bring up the correct information.
I am also unsure about how search engines would treat these pages?
Maybe someone else can come up with an even better approach for this?
Thank you in advance for your help.

You have a few options for how to do this. The simplest way that matches your requirements would be to add the following to your .htaccess file:
RewriteEngine on
RewriteRule ^/plugins/(.*)$ /yourscript.php?plugin=$1 [L]
The above pass all requests to /plugins/anything to yourscript.php, from which you can access the plugin name using $_GET['plugin'].
If "plugins" is simply an example, and you want to be able to use /anything/anything - then you may wish to look at passing all requests to your PHP script, and then parsing the requested URL.
To do that, you'd use something like this in your .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /yourscript.php [L]
To break that down, the above tells Apache to rewrite all requests where the file does not exist (i.e. images/css/js, etc.) to yourscript.php.
From there, you can access the whole URL via $_SERVER['REQUEST_URI']. Which you can break down with string functions, regular expressions, and so on.

why not make an actual directory ?
Eg.
domain.com/plugins/whatever
domain.com/plugins/anotherpagename
whatever and anotherpagename would both be directories.
Then write the html file as index.html inside the directory.
No htaccess needed and you could still access using the same url as above.

I don't know if you are using any framework. I have solution using codeigniter. The same can be simulated using other frameworks / core PHP.
codeigniter specific solution:
In config/routes.php define
$route['plugins/(:any)'] = "plugins/getPageFromDb/$1";
After this, in browser the url will be same 'domain.com/plugins/whatever' but actually control will hit 'getPageFromDb' function of the 'plugins' controller with 'whatever' as the parameter.
In 'getPageFromDb' function you should write your code to get the page from db based on the parameter 'whatever' and echo the output directly or through a view template (depending on your logic / scenario).
And for performance you may keep a static version of the html page and write a relative check in the 'getPageFromDb' function to decide whether to get the page from static or from db.
Considering the url format and the well formed HTML rendering, it should be Search Engine friendly page.

Related

.htaccess rewrite with WordPress plugin

I am working on building a WordPress plugin for a custom WordPress multisite network and have a few files that use URL variables to load information from a second database (not the WordPress database).
In the version built outside of WordPress by navigating to http://website.com/NAME-HERE it would check to see if it is a username in my database, if not check to see if its a group in my database and load the file that corresponds to if its a username or group.
Now I'm totally lost about implementing this into WordPress Multisite. As far as I know plugins can't make .htaccess rewrites? How do I make it work on all the network sites?
If not whats the best way to accomplish this?
Do I need to place my pretty.php & .htaccess rewrites into my root directory and point the pages to the files located in the plugin? If so how does this work with multiple themes?
At this point I figured my best bet was to reach out to the StackOverflow community for assistance or direction.
.htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(\w.+)$ ./pretty.php?pretty=$1 [QSA]
ErrorDocument 404 /404.php
pretty.php
// First check if passed pretty parameter is a username.
if(checkIfUserByUsername($_GET['pretty']))
{
$_GET['username'] = $_GET['pretty'];
include("USERNAME.php");
// If not a username, check to see if it's an event.
}else if(checkIfStreamByPretty($_GET['pretty'])){
$_GET['id'] = getStreamIdFromPretty($_GET['pretty']);
include("GROUP.php");
}else{
// If it's none, redirect to the 404 page.
include("404.php");
}
There are a handful of ways you could approach this, if I am understanding what you want to achieve. You likely don't need to use any rewrites.
The easiest solution would be to add your "pretty.php" code to your header.php file in your Wordpress template. This will load on every request to the front end of the website. If you need it to load the code only on a specific page, simply check for what page you are on using is_page.
for example, in your header.php:
if(is_page("groups")){
if(checkIfUserByUsername($_GET['pretty']))
{
// the rest of your code
}
}
If you want to write a Wordpress plugin, you just need to use "add_action" in your plugin:
add_action('wp_head', 'function_containing_your_code');
Again, this will load on every page so simply check that your are on the page you want to load your code on.
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head
https://developer.wordpress.org/reference/functions/is_page/
Also, you can edit your .htaccess file just like you can edit any file that your user has permission to edit. Assuming you are running an apache server, your .htaccess file needs to have permissions that allow the file to be edited and you can edit the file with PHP. for example:
$file = fopen("/path/to/.htaccess", "a+");
fwrite($f, "RewriteRule ^(\w.+)$ ./pretty.php?pretty=$1 [QSA]");
fclose($f);
Many people would say that it is a security risk to have PHP writing to your .htaccess file. I would say that in some circumstances that is true, but certainly not always. Make you understand permissions before allowing PHP to write to your .htaccess file.
In addition to John Gile's answer please sanitize the Get parameters. You can read about some sanitizing option's here
In your questions context something like $username = sanitize_text_field( $_GET['pretty'] ); Should be sufficient. But please take a deeper look at what needs sanitizing.
Regarding your original Question the first approach John suggested seems to be the better one.
Consider the moment two separate request are requesting the same url with the same username. Since File Reading/Writing is a blocking Stream one of the requests have to wait for the stream to close and the website won't render until this happens.
If you bypass this with an additional stream or whatever your risking to end up with duplicate entries or worse a corrupted file which could lead to Server Errors.
Edit
I'am not quite sure what you are trying to achieve with including include('USERNAME.php') are you creating a dedicated php file for every user that signs up for your "multi-site network"? If that is the case I think you made wrong decisions when planing this.
Usually when you want to share, control or alter behavior depending on external resources you'd fetch data in the JSON data format.
Now if I were in your shoes I'd create a REST web service that returns the JSON depending on the username get parameter and control the output depending on the data coming in.
Creating a api is rather complex and depending on your needs you'd go with whatever tool fits these best. I personally enjoyed working with apigility for rather complex things and lumen for small things. You can also create this yourself if you choose, too.
After creating the api you then could easily get the JSON with file_get_contents() described here or use whatever rest tool you can find for php.

how to Blog urls work?

Hello guys I was wondering how blog articles work I mean they are stored in a database right? so how come when I go to an articles its like this:
www.something.com/seths_blog/2015/02/shoes-that-dont-fit-and-free-salt.html
for example I mean do they use php create and create these blogs on files on there htaccess or there is a way to do it efficiently I mean they got to put in it in a Database because sorting comments and so are much more efficient rating and such or polls are well really need the answer thank you
Edit your .htaccess file to add this:
#forward all traffic to index to be handled there except resources
RewriteCond %{REQUEST_URI} !(\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.js|\.css)$
RewriteRule (.*) index.php [QSA]
Note that any other file types you don't want to be forwarded will need to be added to the list of file types above. What this line is doing is forwarding all file requests to your index.php file except the ones you declare (like images).
Next, go to your index.php file and add this code:
echo "My URL is:" . $_SERVER['REQUEST_URI'];
This is the basic answer. Now, any question you have beyond this is a matter of basic PHP (and probably MySQL). You can manipulate that data in a limitless combination of ways.

Using mod_rewrite to substitute variable used in URL

I've gone through a few different questions like:
Rewrite for all URLs
Can mod_rewrite convert any number of parameters with any names?
Creating dynamic URLs in htaccess
Which helped me change one set of urls from domain.com/script2.php?d=1 to domain.com/(d), but now I'm stuck with something that I can't find an answer for. Currently, I have a set of URLs that are set up as:
domain.com/script.php?a=1
While I know how to change those URLs to domain.com/(a) this doesn't quite help me with this one because variable A is just a numerical identifier, so going from domain.com/script.php?products=1 to domain.com/1 doesn't do me a lot of good.
Instead, it's variable B which is actually the descriptor, ProductName. So what I'm trying to do is have it so that rather than domain.com/(a), I can get domain.com/(b). There is a complication. The reason that the original set up used variable A is that multiple products use the same descriptor in variable B, so I also need to include variable C which differentiates them, so I need the URL to be domain.com/(b)-(c).
Bonus! Remember how I said I had another script that I'd changed from domain.com/script2.php?d=1 to domain.com/(d)? Well, it'd be super awesome if I could set up my this current script to display not as domain.com/(b)-(c) but instead as domain.com/(d)/(b)-(c) because domain/(d) is actually the search page for this other script, so it's a really logical flow and would really simplify browsing, and would let users intuitively move between the search and the products without much work.
I have no idea if this is even possible, but any help would be appreciated.
Why not just rewrite everything back to your script file?
RewriteEngine on
RewriteBase /
RewriteRule .* index.php [L]
Will rewrite everything back to index.php. From there you can parse the $_SERVER['REQUEST_URI'] variable in PHP. From there you can decide what page to load based on the given url.
If you have any other folders in the same directory of the rewrite rule above, you can put another .htaccess file inside those that have RewriteEngine Off if you don't want them to be rewritten back to index.php. That is what you will need for a css file or site images.
Using this method, you could always do something like this.
domain.com/products/1
or, domain.com/search/blahblah

.htaccess Rewrite/Redirect mod or PHP script

So currently E-commerce company I'm working for is in transition from an .NET based platform to the Magento PHP based site. The issue I'm running into is that we have 1000's of our current landing pages ranked well on search engines. There's no way for me to 301 all of these pages within the new platform - Magento, and I know I can't add 1000's of static redirects to the .htaccess file because of performance issues.
So my question is this, Is there a way to create rewrite or redirect rules for variables within our DB that generate the indexed pages URL's. If there is, performance wise would it be smarter to do this solely with the .htaccess file, just PHP Scripts or a combination of both?
Here's a sample of one of our current URLs and sample of what we'd like it to be redirected to:
Current URL
/Clear_For_Life-Aquariums_Bowls-AT-70_180-AQAQ-ct.html
Here's a breakdown of the data we use to generate the rewrite;
/Clear_For_Life = VendorName Column in DB
Aquariums_Bowls = Subcategory Column in DB
AT = VendorCode Column in DB
70_180 = PriceRange Column in DB
AQAQ = CategoryId Column in DB
Desired URL to be Redirected to;
/clear-for-life-aquariums-bowl
Any help or advice here would be greatly appreciated.
So my question is this, Is there a way to create rewrite or redirect rules for variables within our DB that generate the indexed pages URL's. If there is, performance wise would it be smarter to do this solely with the .htaccess file, just PHP Scripts or a combination of both?
This sounds like a job for RewriteMap. You'll need access to either the server or vhost config and create a map. You can use this mapping to call a script that can fetch something from your DB, then decide what the new URI needs to look like. The simplest usage of RewriteMap could be:
RewriteMap remap prg:/path/to/script
And later you can simply do:
RewriteRule ^(.*)$ /${remap:$1|$1} [L]
The /path/to/script would need to take an input like Clear_For_Life-Aquariums_Bowls-AT-70_180-AQAQ-ct.html, parse it, and correctly output clear-for-life-aquariums-bowl.
I don't believe you can change case or replace characters ('_' to '-') using mod rewrite.
Why can't you 301 all these pages?
If they are being accessed with .NET then where ever you do the routing / parse the url there should be a line of code to do the php redirect.
I say use htaccess, and write a simple utility to generate said htaccess file from a list of the 301 details.

php based website that displays page content based on URL?

I would like to make a website that is php and only requires one php document to display the content. It's kinda hard to explain, so let me try my best.
Some websites use a directory based system such as this:
web.URL.com/index.htm
web.URL.com/about.htm
web.URL.com/blog.htm
and so on.
This involves creating a text file for each page.
So, the goal here is to create one page that acts like a frame, and displays content based on the Url, so it will be acting like the above method, but is only one page. I'm pretty sure you can do this, but don't know the proper way to word it or what vocabulary to use when typing it in to google.
Some questions you may have:
Q:Why not use parameters like this:
web.url.com?pgid=some+page
A: I would like the url to be as clean as possible when it comes to the visitor typing the url. For example, this is much easier to remember:
web.url.com/about
than this:
web.url.com?p=about
Q: Wordpress??
A: We want our own stuff. Wordpress is great, but not for our project.
Q: JQuery?
A: PHP please.
Thank you in advance!
With PHP alone, I don't think it's possible. However, it's likely that your webserver is running Apache, which makes this task fairly straightforward by transforming your pretty URLs into ugly URLs (with query strings) that your PHP script can handle. Your visitors have no idea this is happening; they aren't redirected or anything.
I strongly recommend you take a look at this tutorial, and its followup. The second tutorial contains the information you need for this task (starting in this section), but I strongly recommend reading the first tutorial to gain a deeper understanding of what you're doing.
Essentially, those tutorials will teach you how to specify (ugly, scary-looking) URL-rewriting rules in a file called .htaccess. These rules will transform (or "rewrite") your pretty URLs into less pretty ones that your PHP script can handle.
For example, yoursite.com/about would actually be accessing yoursite.com/index.php?page=about, or something along those lines.
For some sample code, here's a snippet 95% copied and pasted from this tutorial:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
As that link explains, it will forward all requests to index.php, unless an actual file or directory is being requested.
Use a RewriteRule based .htaccess. Then you can have all non-existing files redirected (internally in Apache) to a general index.php with the requested path as a query string ?p=about. The redirecting is handled internally, so http://example.com/about is the external URL to that page.
You can have a switch statement checking $_GET values and output the page based on the provided parameter. Also, you will have to add some mod_rewrite rules to route those requests.
Use PHP URL rewrite. PHP will enteprate part of your URL as query string

Categories