Is there a way to insert relative URLS in php code such as /forums/(forumID)/ into tags while setting up my site? Then when I am trying to get which forumID the current page is, to get it via a $_GET request without using a template system like Smarty, CakePHP etc or Apache rewrite module? Or is it a huge headache? I just want to be able to not be bound to one web server type (Apache).
Clean urls are fairly easy to do, but if the web pages are vastly different, it may cause some problems.
You'll need to edit your .htaccess file and add something similar to this
RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)$ index.php?page=$1
#This will process http://example.com/forum as http://example.com/index.php?page=forum
RewriteRule ^([a-zA-Z0-9]+)/$ index.php?page=$1
#This includes the trailing slash
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)$ index.php?page=$1&id=$2
#This will process http://example.com/forum/512 as http://example.com/index.php?page=forum&id=512
This is a good source for more information http://www.desiquintans.com/cleanurls
... carried on from OP comments.
These frameworks read the request again in their respective languages to allow the framework to route to specific controllers, but they still need the webserver to be setup to send the request to the framework in the first place.
Client requests http://example.com/forums/123
After DNS lookup, request hits server at 127.0.0.1:80
Webserver (eg Apache) listens for port 80 and accepts request
Apache routes request to server-side script
This is the journey as the web server sees it. It needs to read the request before it even hits the server-side scripting language (PHP/Python/Ruby etc).
The server-side languages can then re-read the URL once the webserver has hit the front controller as they please.
The main reasons to have clean urls from an architecture point of view:
They are not tied to any programming language. If you have .php or any other extensions, you'd have to set up your server to accept .php extensions for other languages if you switch to ASP.net.
They are are easy to route in any language or server setup. All modern servers I know of have modules to route urls.
Note that to use a programming language to route the urls, you still have to set up your server to direct everything to a bootstrap file. Honestly, you are not getting around server configurations of some kind no matter what.
Conclusion: your logic for wanting your project set up this way will not work without doing some server setup.
Related
I have a problem,
I need to know how to create a subdomain dynamically.
http://example.com/user.php?id=ajithjojo
I want it to work like
http://ajithjojo.example.com/
how it's possible. I checked all of StackOverflow discussions but I didn't get a right answer what i need
This has nothing to do with the htaccess.
You could setup your webserver so that *.example.com would point to a specific public root. In that public root resides a php script that checks the database to see if the host / username should exist.
So your first URL creates a record in the database that says that ajithjojo exists.
Then when visiting the second URL, the script sees that the domain exists and then does dynamic stuff.
If it does not exist the script throws a 404 header, or redirects somewhere.
You either need to implement some logic to add virtual hosts to the apache http server (complex and questionable) or you use a default host (one that responds to all incoming requests that are not handled by existing vhosts) and implement internal rewriting rules in that one. This allows you to simply hand out references to such "subdomains" (actually host names).
Those rewriting rules could look like that:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$
RewriteRUle ^ %{REQUEST_URI}?user=%1 [END]
Obviously you will need to adjust that to your actual setup, but it should point you into the right direction. For example you could use an implementation that evaluates the requested host instead of relying on a specific http get argument as shown above. But those are implementation details that you have to decide yourself.
In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.
This implementation will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.
And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).
Follow this tutorial to set subdomains based on usernames
Im looking to rewrite my URL so it is more SEO and user friendly, I have spend a lot of time on this and am struggling to get my head around how the rewrite process works.
One of the issues I'm having is that my Site is broken up in sections using sub domains, The site is a comparison site that will allow you to find details on a product or compare the product against another. The cameras section is under 'cameras.specced.co.uk' and there will be other sections I will make in the future such as 'drones.specced.co.uk' and 'phones.specced.co.uk'.
Currently I load page information via numeric ID's for example, this is the URL that fetches all specifications for the Canon 1300D:
http://cameras.specced.co.uk/compare.php?i=98
I would like to rewrite this into something like this
http://cameras.specced.co.uk/compare/98
For the pages that compare 2 products side by side, the URL currently looks like this, (URL fetches comparison of Canon 1300D VS Nikon D5300)
http://cameras.specced.co.uk/compare.php?1=98&2=111
I would like to rewrite this URL into something like this
http://cameras.specced.co.uk/compare/98-vs-111
This is what I have come up with, however does not work
RewriteRule ^i/([0-9]+)/?$ compare.php?i=$1 [NC,L] # Handle product requests
I greatly appreciate any help
You are looking for something like that: two rules, typically first the more specialized:
RewriteEngine on
RewriteRule ^/?compare/(\d+)-vs-(\d+)$ /compare.php?i1=$1&i2=$2 [END]
RewriteRule ^/?compare/(\d+)$ /compare.php?i=$1 [END]
Those rules will work in both, dynamic configuration files (".htaccess") and in the real http servers host configuration. If you decide to use dynamic configuration files then you need to take care to actually enable their interpretation first. Take a look at the AllowOverride directive for that: https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride
If you are using a really old version of the apache http server then you may have to replace the [END] flag with the [L] flag. You will then get an internal server error otherwise and find according hints in the http servers error log file.
A general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).
I need some help. Whenever I am making a PHP get request, say for name, how would I change this:
http://website.com/page?name=Something
to this:
http://website.com/page/Something
Thanks for your time!
Use htaccess
RewriteEngine on
RewriteBase /
RewriteRule page/([0-9a-zA-Z]+)/ page?name=$1
What you want is to be able to route requests. It depends on how your application receive requests
If you're using apache with mod_php, the routing corresponds to your filesystem (path in the request → path of the file). This is a very bad form of routing, and confuses a lot of beginners, because you have basically no power on how the requests are handled. Your best solution is to use Apache URL Rewriting, which will allow you to transform /page/something into /page?name=something so that it can be handled properly by mod_php.
If you have more control on your httpd, you should try some PHP routing libraries like https://github.com/chriso/klein.php or http://zaphpa.org/ that will give you a better control on how your requests are dispatched.
I'm looking to write a basic PHP file caching driver in a PHP application that routes all traffic to a front controller. For example's sake, assume the following simplified setup using apache mod_proxy_balancer:
In a single-server environment I would cache request responses on disk in a directory structure matching the request URI. Then, simple apache rewrite rules like the following could allow apache to return static cache files (if they exist) and avoid the PHP process altogether:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /front_controller.php [L]
Obviously, this is problematic in a load-balanced environment because the cache file would only be written to disk on the specific PHP server where the request was served up and the results cached.
Solving the issue ...
So, to solve this problem, I figured I could knock out some code to have the individual back-end PHP servers write/delete cache data to the load balancer. However, being mostly ignorant as to the capabilities of mod_proxy_balancer (and any other load balancing options, really), I need some outside verification for the following questions:
And the questions ...
Is it possible to do some form of checking like the above RewriteRules to have the front-facing load balancer serve up a static file before sending off requests to one of the backend servers?
Is this even advisable? Should the load balancer be allowed to route traffic exclusively and not be bothered with serving up static content?
Would it be better to just use an acceptable TTL on the cached files at the PHP server level and deal with an accepted level of stale cache overlap?
Finally, apologies if this is is too broad or has already been answered; I'm not really sure what to search for as a result of my aforementioned ignorance on the load-balancing subject.
For the simplest solution, you can use NFS. Mount a file system via NFS on all of the PHP servers and it acts like local storage, but is the same for all servers. To get a little more sophisticated, use something like Nginx or Varnish that can cache what is on the NFS file system.
Using memcache is also a viable alternative, which is a distributed memory based storage system. The nice thing about memcache is that you don't need to manage cache clearing or purging if you don't want to. You can set TTL for each cached item, or if memcache gets full, it automatically purges cached items.
This sounds like something Nginx could do easily, and would remove the need to write to files on disk.
Nginx can do the load balancing and caching, here's a tutorial on it:
http://nathanvangheem.com/news/nginx-with-built-in-load-balancing-and-caching
I see many, many sites that have URLs for individual pages such as
http://www.mysite.com/articles/this-is-article-1
http://www.mysite.com/galleries/575
And they don't redirect, they don't run slowly...
I know how to parse URL's, that's easy enough. But in my mind, that seems slow and cumbersome on a dynamic site. As well, if the pages are all staticly built (hende the custom URL) then that means all components of the page are static as well... (which would be bad)
I'd love to hear some ideas about how this is typically accomplished.
There are many ways you can handle the above. Generally speaking, there is always at least some form of redirection involved - although that could be at the .htaccess level rather than php. Here's a scenario:
Use .htaccess to redirect to your php processing script.
Parse the uri ($_SERVER['REQUEST_URI']) and ascertain the type of content (for instance, articles or galleries as per your examples).
Use the provided id (generally appended to the end of the uri, again as in your examples) to obtain the correct data - be that by serving a static file or querying a database for the requested content.
This method is a very popular way of increasing SEO, but as you rightly highlight there can be difficulties in taking this approach - not typically performance, but it can make development or administration more troublesome (the later if your implementation is not well thought out and scalable).
Firstly, when comparing /plain/ URL rewriting at the application level to using /plain/ CGI (CGI can be PHP, ISAPI, ASP.NET, etc.) with serving static pages, serving static files will always, always win. There is simply less work. For example, in Windows and Linux (that I know of) there are even enhancements in the kernel for serving static files on a local drive via HTTP. To further make the point I even found a benchmark using several servers and OSs: http://www.litespeedtech.com/web-server-performance-comparison-litespeed-2.0-vs.html#RESULT Note that serving static files is dramatically faster than using any type of CGI
However, there can potentially be performance and scalability gains by using rewritten URLs effectively and it is done with caching. If you return proper cache headers (see cache-control directive in HTTP documentation) then it enables downstream servers to cache the data so you won't even get hits on your site. However, I guess you could get the same benefit with static pages :) I just happen to read an article on this very topic a day or two ago at the High Scalability blog: http://highscalability.com/strategy-understanding-your-data-leads-best-scalability-solutions
A rewrite engine is the best approach as they are fast and optimised. Allowing your Server-Side scripting to use just plain local vars.
Apaches mod_rewrite is the most common.
It's usually done via a rewrite engine, either in the server (via something like mod_rewrite in Apache) or in the web application (all requests are routed to the web application, which looks for a route for the path specified).
In my case, I stick to the web framework with this feature already built-in. (CodeIgniter)
... As well, if the pages are all staticly
built (hende the custom URL) then that
means all components of the page are
static as well... (which would be bad)
... yes, this is very bad indeed. :o
It is possible to rewrite at
The server level in either the .htaccess file or the httpd.conf or vhosts.conf file. This is typically faster than the next level of rewriting which is done on the application level.
The application level (in this instance with PHP). You can write custom redirects that analyse the URL and redirect in some way based on that. Modern web frameworks such as the Zend Framework (ZF) use routes to control URL rewriting. The following is an example of a static route with ZF
$route = new Zend_Controller_Router_Route_Static('latest/news/this/week',
array('controller' => 'news'));
Which would redirect any request from http://somedomain.com/lastest/news/this/week to the news controller.
An example of a dynamic route would be
$route = new Zend_Controller_Router_Route('galleries/:id', array('controller' => 'gallery'));
Where the variable $id would be availbe to that controller (and using our example above would be 575)
These are very useful tools to that allow you to develop an application and retrospectively change the URL to anything you want.
A very simple way is to have a CGI parse the PATH_INFO portion of the URL.
In your example:
http://www.example.com/articles/12345 (where "articles" is a CGI script)
^CGI^ ^^^^^^PATH_INFO
Every thing after the script name is passed to the script in the PATH_INFO CGI header.
Then you can do a database lookup or whatever you wish to generate the page.
Use caution when accessing this value as the IIS server and Apache server put different portions of the URL in PATH_INFO. (IIRC: IIS incorrectly uses the entire URL and Apache prunes it as stated above.)
On apache servers mod_rewrite is the most common for this, it's an apache mod which allows you to rewrite request urls to other urls with regular expressions, so for your example something like this would be used:
RewriteEngine ON
RewriteRule ^articles/(.*) articles.php?article=$1 [L]
RewriteRule ^galleries/(\d*) galleries.php?gallerie=$1 [L]
This costs hardly any time, and in practice is just as fast as having the url:
www.mysite.com/galleries.php?gallerie=575 but looks way better
I have used this method preiously - you just need to add the file extensions that should not be redirected in the regex and then everything else is handled by php so you don't need to be going into your .htacces file
suceed with urls