301 Redirects | Response Headers / React *

+ REACT

Tool to check headers

https://httpstatus.io/

 

301s bluessssss301 Server Side Redirects301s apache

https://ignitevisibility.com/the-ultimate-list-of-301-redirect-examples-for-seo/

breakdown of all lists –


A 301 redirect is a permanent redirect when a page on your site is removed or moved. It is an HTTP (Hypertext Transfer Protocol) response status code that shows the response from the server where the page is hosted to the browsers that requested the URL.

 

The 301 redirect ensures authority is passed from the old to the new URLs, which is why you should avoid a 302 which is considered for temporary change in URLs. Using the correct redirect type prevents a those huge dips in traffic and Google and alike will be able to know where they are going without guessing..

When URLs have changed, each old page must have a 301 redirect pointing to the new page. Absolutely critical. Even if there isn’t an equivalent page you can redirect to a relevant page. It’s much better than getting to a 404 not found page.

If you want to ensure search engines are able to pick up on redirects quickly, then make sure to use server-side redirects. If content has moved permanently, use a 301 redirect. If it has moved temporarily, use a 302 redirect. Back button: client-side redirects break the Back button.

Overall Issue:

https://stackoverflow.com/questions/7583461/redirect-to-page-and-send-custom-http-headers

Im afraid, all the answers are wrong and misleading!

It's impossible to redirect to a page with custom headers set, no matter what language or framework you use. In other words, there's no way to trigger an HTTP redirect and cause the client (browser) to add a custom header.

You might be thinking that using multiple header() calls should work just fine. But it won't. You're setting the custom headers for the response which is instructing the browser to redirect, not for the redirect itself.

The only way for a site to instruct a browser to issue an HTTP request with a custom header is to use Javascript and the XMLHttpRequest object. And it needs CORS implemented on the target server to allow such ajax requests.

Please note that a page can not set HTTP request headers unless it's making an async request using XMLHttpRequest. Meaning that you can't do such redirection with the custom header on the client-side as well.

 


https://www.contentkingapp.com/academy/redirects/

Client-side redirects

A client-side redirect is a forwarding method in which a visitor's browser handles redirection. Using client-side redirects has several drawbacks, namely:

  • SEO: search engines may not pass authority when client-side redirects are used, because they may not be aware of the redirects yet in the case of JavaScript redirects, or they may not treat it as a redirect because of the refresh time. Keep in mind that, in order for search engines to see a JavaScript redirect, they need to execute it. And their resources for JavaScript execution are limited. That's why it usually takes a while before the redirect is picked up and processed. In case of the meta refresh: if the refresh time is set to "0", search engines will likely treat it as a 301 redirect and pass authority. If you want to ensure search engines are able to pick up on redirects quickly, then make sure to use server-side redirects. If content has moved permanently, use a 301 redirect. If it has moved temporarily, use a 302 redirect.
  • Back button: client-side redirects break the Back button. When trying to use the Back button, visitors will immediately be sent to the URL they were redirected to.
  • Support: not all browsers support client-side redirects.

For all these reasons, we strongly recommend against using client-side redirects.

Due to the nature of this article, it is still important to describe the client-side redirects:

Meta refresh redirect

A meta refresh redirect is implemented using the meta refresh element, located in the <head>-section. It's used to instruct a browser to refresh a page or load another URL after a certain number of seconds.

Here's an example of what the meta refresh redirect looks like to send a visitor to https://www.contentkingapp.com/ after loading a page:

<meta http-equiv="refresh" content="0; url=https://www.contentkingapp.com/">

Frequently Asked Questions

JavaScript redirect

A JavaScript redirect is used to instruct a browser to load another URL. An example of what a JavaScript redirect may look like when we're sending visitors to https://www.contentkingapp.com/ after rendering the page:

<script>window.location.replace("https://www.contentkingapp.com/");</script>

Frequently Asked Questions

What are the best practices for redirection?

When using redirects, keep the best practices below in mind, to make sure you offer your visitors an optimal user experience and preserve as much page authority as you can.

Avoid redirects whenever you can

Yes, you read it correctly: avoid using redirects whenever you can. They increase load time and waste crawl budget.

Please note that it's totally fine to use 301 redirects for configuring your web server so that it serves URLs according your preferences.

 


 

 

 

 

https://stackoverflow.com/questions/58233324/how-to-add-http-headers-in-react-js-apps-response

 

https://stackoverflow.com/questions/44354763/how-do-i-get-http-headers-in-react-js

 

You cant get current page headers without sending a http request via javascript. See this answer for more info.

Add a dummy api url on your server and hit it after your page loadn then you can get the headers.

class App extends React.Component{
    //some code
    componentDidMount(){
       fetch(Some_API).then(response=>{
           console.log(response.headers)
       })
    }
    //some code
}

 

https://stackoverflow.com/questions/50088892/how-to-send-http-headers-in-reactjs-using-fetch

 

Try this

fetch('your_url', { 
   method: 'get', 
   headers: new Headers({
     // Your header content
   })
 });

 

 


 

 

https://surajsharma.net/blog/nextjs-server-side-redirect

 

301 redirect in Next.js

 

To do a server side redirect in Next,

 

First, create a server side rendering page component inside the /pages folder

 

 ./pages/[code].jsx

const RedirectURL = () => {
 return null;
}

export default RedirectURL;

 

Next, define and export the getServerSideProps function in the same file

 

export const getServerSideProps = async (context) => {
  const { res } =  context;
  res.writeHead(301, { location: "https://google.com" } );
  res.end();
}

 

The res.writeHead method sets the response header, the first argument is a 3-digit HTTP status code and the last argument is the response headers object.

 

the location property of the response headers object contains the destination URL.

 

The res.end() method signals to the server that all of the response headers and body have been sent. The res.end() method must be called on each response otherwise the response will never resolve or will result in the HTTP 502 error status code.

 

Nginx – Redirects

https://twiz.io/blog/nginx-301-redirect/

https://www.digitalocean.com/community/tutorials/how-to-create-temporary-and-permanent-redirects-with-nginx

 

 

https://airbrake.io/blog/http-errors/301-moved-permanently

301 Moved Permanently: What It Is and How to Fix It

November 23, 2017HTTP Errors

A 301 Moved Permanently is an HTTP response status code indicating that the requested resource has been permanently moved to a new URL provided by the Location response header. The 3xx category of response codes are used to indicate redirection messages to the client, such that the client will become aware that a redirection to a different resource or URL should take place.

It can be a challenge to differentiate between all the possible HTTP response codes and determine the exact cause of a message like the 301 Moved Permanently code. There are dozens of possible HTTP status codes used to represent the complex relationship between the client, a web application, a web server, and often multiple third-party web services, so determining the cause of a particular status code can be difficult. In this article we’ll examine the 301 Moved Permanently code by looking at a few troubleshooting tips, along with some potential fixes for common problems that might be causing this issue, so let’s get started!

The Problem is Server-Side

All HTTP response status codes that are in the 3xx category are considered redirection messages. Such codes indicate to the user agent (i.e. your web browser) that an additional action is required in order to complete the request and access the desired resource. Unlike gateway related 5xx response codes, like the 502 Bad Gateway Error we’ve looked at recently, which may indicate issues either on an upstream server or the client, the 301 Moved Permanently code generally indicates an issue on the actual web server hosting your application.

That said, the appearance of a 301 Moved Permanently is usually not something that requires much user intervention. Most browsers should automatically detect the 301 Moved Permanently response code and process the redirection action automatically. The web server hosting the application should typically include a special Location header as part of the response it sends to the client. This Location header indicates the new URL where the requested resource can be found. For example, if a request comes in to access the URL https://airbrake.io, but the web server is configured to forces redirection to a secure version using https, the server response will include the Location: https://airbrake.io header. This tells the browser that it should redirect this request (as well as all future ones) to https://airbrake.io to the secured URL of https://airbrake.io. In most cases, the browser will automatically detect this 301 Moved Permanently response code, read the new Location URL, and redirect the request to that new location. It is considered best practice to use a 301 Moved Permanently redirection to transition a user agent from HTTP to the secure HTTPS. Thus, if you attempt to go to the insecure URL of https://airbrake.io right now, you’ll automatically be redirected to the HTTPS version of the site (https://airbrake.io).

Since the 301 Moved Permanently indicates that something has gone wrong within the server of your application, we can largely disregard the client side of things. If you’re trying to diagnose an issue with your own application, you can immediately ignore most client-side code and components, such as HTML, cascading style sheets (CSS), client-side JavaScript, and so forth. This doesn’t apply solely to web sites, either. Many smart phone apps that have a modern looking user interface are actually powered by a normal web application behind the scenes; one that is simply hidden from the user. If you’re using such an application and a 301 Moved Permanently occurs, the issue isn’t going to be related to the app installed on your phone or local testing device. Instead, it will be something on the server-side, which is performing most of the logic and processing behind the scenes, outside the purview of the local interface presented to the user.

All of that said, if your application is generating 301 Moved Permanently codes improperly or unexpectedly, there are a number of steps you can take to diagnose the problem.

Start With a Thorough Application Backup

As with anything, it’s better to have played it safe at the start than to screw something up and come to regret it later on down the road. As such, it is critical that you perform a full backup of your application, database, and so forth, before attempting any fixes or changes to the system. Even better, if you have the capability, create a complete copy of the application onto a secondary staging server that isn’t “live,” or isn’t otherwise active and available to the public. This will give you a clean testing ground with which to test all potential fixes to resolve the issue, without threatening the security or sanctity of your live application.

Diagnosing a 301 Moved Permanently Response Code

A 301 Moved Permanently response code indicates that the server believes that the requested resource is invalid and that the request should be redirected to a new, “proper” URL. I use the word believes here because it’s entirely possible that the server is misconfigured or bugged in some way, which is causing it to provide 301 Moved Permanently codes for resources/URLs that are totally valid. Thus, a large part of diagnosing the issue will be going through the process of double-checking what resources/URLs are generating 301 Moved Permanently response codes and determining if these codes are appropriate or not.

That said, if your application is responding with 301 Moved Permanently codes that it should not be issuing, this is an issue that many other visitors may be experiencing as well, dramatically hindering your application’s ability to service users. We’ll go over some troubleshooting tips and tricks to help you try to resolve this issue. If nothing here works, don’t forget that Google is your friend. Don’t be afraid to search for specific terms related to your issue, such as the name of your application’s CMS or web server software, along with 301 Moved Permanently. Chances are you’ll find others who have experienced this issue and have come across a solution.

Troubleshooting on the Server-Side

Here are some additional tips to help you troubleshoot what might be causing the 301 Moved Permanently to appear on the server-side of things:

  • Check the Server Configuration Files – Your application is likely running on a server that is using one of the two most popular web server softwares, Apache or nginx. At the time of publication, both of these web servers make up over 84% of the world’s web server software! Thus, one of the first steps you can take to determine what might be causing these 301 Moved Permanently response codes is to check the configuration files for your web server software for unintentional redirect instructions.

To determine which web server your application is using you’ll want to look for a key file. If your web server is Apache then look for an .htaccess file within the root directory of your website file system. For example, if your application is on a shared host you’ll likely have a username associated with the account on that host. In such a case, the application root directory is likely something like /home/<username>/public_html/, so the .htaccess file would be at /home/<username>/public_html/.htaccess.

If you located the .htaccess file then open it in a text editor and look for lines that use RewriteXXX directives, which are part of the mod_rewrite module in Apache. Covering exactly how these rules work is well beyond the scope of this article, however, the basic concept is that a RewriteCond directive defines a text-based pattern that will be matched against entered URLs. If a matching URL is requested by a visitor to the site, the RewriteRule directive that follows one or more RewriteCond directives is used to perform the actual redirection of the request to the appropriate URL. Therefore, if you find any strange RewriteCond or RewriteRule directives in the .htaccess file that don’t seem to belong, try temporarily commenting them out (using the # character prefix) and restarting your web server to see if this resolves the issue.

On the other hand, if your server is running on nginx, you’ll need to look for a completely different configuration file. By default this file is named nginx.conf and is located in one of a few common directories: /usr/local/nginx/conf, /etc/nginx, or /usr/local/etc/nginx. Once located, open nginx.conf in a text editor and look for the return or rewrite directives. For example, here is a simple block directive (i.e. a named set of directives) that configures a virtual server by creating a redirection from invalid-domain.com to the proper valid-domain.com URL:

server {
    listen 80;
    listen 443 ssl;
    server_name invalid-domain.com;
    return 301 $scheme://valid-domain.com$request_uri;
}

Rewrite directives in nginx are similar to the RewriteCond and RewriteRule directives found in Apache, as they tend to contain more complex text-based patterns for searching. Either way, look through your nginx.conf file for any abnormal return or rewrite directives and comment them out before restarting the server to see if the issue was resolved.

  • Check the Logs – Nearly every web application will keep some form of server-side logs. Application logs are typically the history of what the application did, such as which pages were requested, which servers it connected to, which database results it provides, and so forth. Server logs are related to the actual hardware that is running the application, and will often provide details about the health and status of all connected services, or even just the server itself. Google “logs [PLATFORM_NAME]” if you’re using a CMS, or “logs [PROGRAMMING_LANGUAGE]” and “logs [OPERATING_SYSTEM]” if you’re running a custom application, to get more information on finding the logs in question.
  • Application Code or Script Bugs – If all else fails, it may be that a problem in some custom code within your application is causing the issue. Try to diagnose where the issue may be coming from through manually debugging your application, along with parsing through application and server logs. Ideally, make a copy of the entire application to a local development machine and perform a step-by-step debug process, which will allow you to recreate the exact scenario in which the 301 Moved Permanently occurred and view the application code at the moment something goes wrong.

No matter what the cause, the appearance of a 301 Moved Permanently within your own web application is a strong indication that you may need an error management tool to help you automatically detect such errors in the future. The best of these tools can even alert you and your team immediately when an error occurs. Airbrake’s error monitoring software provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake’s state of the art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. No matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize exception parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.

 

REDIRECTS

 

Understanding URL Redirects:How to Successfully Redirect Your Web Pages A redirect is a way to forward a person from a URL that may be temporarily or permanently inaccessible to another, relevant URL. The primary purpose of using redirects is to provide a good user experience. Instead of landing on a no longer existing page, a person is automatically redirected to another asset on the topic, allowing them to continue their research. Unfortunately, redirects can affect more than the user experience. In fact, they can influence and affect many aspects of an usability and SEO strategy.For that reason, we believe it is critical that SEOs understand how redirects work, and how to use them properly to retain link authority,rankings and traffic.That’s also exactly why we’ve created this guide. So, from the content below you’ll discover:What are Redirects,How They Work,Why and When to Use Them,The Different Types of Redirects,What are the Most Typical Use Cases for Redirects in SEO,Common Mistakes SEO Make When Redirecting Pages,Best Practices for Using Redirects for SEO.Finally, at the end of this guide, we also answer some of the most frequently asked questions about redirects. But let’s begin at the beginning.

What is a Redirect?A redirect is a method of setting up a connection between an old, potentially no longer existing URL and its active counterpart. Using a simple line of code – more on this in just a moment – a webmaster can specify such a connection and redirect anyone trying to access the old URL to the new page. In its simplest form, a typical redirect looks like a command given to the browser (or a server) to forward a visitor to another page. For example, this redirect code permanently moves visitors trying to access page A on a domain to page B:301 Redirect – https://www.mydomain.com/pageA.html to https://www.mydomain.com/pageB.htmlWith such a redirect command in place, anyone trying to access the /pageA.html file through their browser will be automatically forwarded and will see, /pageB.html instead. (Don’t worry if you don’t understand the code above or what its various elements mean. We’ll discuss that in more detail very soon.) When to Use RedirectsI’ve alluded to one potential scenario – when a page becomes temporarily or permanently inaccessible – however, redirects help with other purposes too. First of all, redirects help both visitors AND search engines, particularly when the content is moved or becomes inaccessible. For visitors, redirects help provide a good user experience. Instead of landing on a 404 page, and having to find other relevant content on the topic on their own, a webmaster may build a redirect connection and ensure that visitors always land on the information they seek. For search engines, redirects mean that their crawlers don’t have to analyze and make sense of broken URLs or internal links. Instead, the engine can save the crawl budget to see live content, understand it and index it properly.Although we will talk about specific redirect use cases at length later in the guide, it would make sense to illustrate the above with some examples. So, when would you use a redirect?For one, when migrating the site from old to a new domain. In this case, all pages have to be redirected to their counterparts on the new domain. You may also be consolidating two or more websites into one. When doing so, you must redirect URLs from those web entities into the single domain you’ll be consolidating them to. Any store whose certain products have become no longer available, out of stock or discontinued should redirect those to the nearest alternatives to provide customers with the most relevant substitute.The store may also run seasonal pages, like Black Friday deals, that remain empty, apart for the limited time when they are needed. In such a case, its owners may decide to redirect them temporarily to other assets and remove the redirect when they need those pages again.Finally, when deleting old pages or content you no longer need, it makes sense to redirect those URLs to other alternatives, even if only to not lose the current SEO impact of those assets.

 

The Different Types of RedirectsWe’ve discussed a handful of redirects already, and if you looked closely, you may have noticed that they all differ from one another. Some redirect content permanently, others forward visitors to another URL only temporarily.Also, some redirects move the entire contents of a website while others target specific assets and so on. Let’s shed some light on this and discuss the different types of redirects. In general, we divide redirects into two categories:Server-side which, as the name suggests, operates on the server level 30x HTTP status codesClient-side, a group of redirects that are triggered by the request for a file by the browser. Meta refreshJavascript redirectsPart 1. Server-Side RedirectsAs the name suggests, the server side redirect occurs on the server. A HTTP request for a file is received by a server, and answered with an appropriate status code, indicating the redirect and its nature – permanent or temporary. There are a number of server-side redirects. The most common are:301 REDIRECT – MOVED PERMANENTLYA 301 redirect is a server-side redirect that permanently redirects users from one URL to another. 301 redirect is an important redirect from a SEO perspective.There is a reason why this redirect is referred to as permanent. It, to put it in the simplest terms, tells the search engine that the original URL is no longer in use and has been replaced by the other page. Based on this information, Google and other search engines will replace the original URL in their index with the one the redirect points to. In many cases, they will also assign whatever link equity the original URL acquired to the new one as well.When to Use 301 Redirects301 should be used when you’ve removed or deleted a page permanently from the site’s architecture, yet want to preserve its traffic, rankings, and links. Use Cases for 301 RedirectsYou've moved your site to a new domain, and you want to make the transition as seamless as possible.People access your site through several different URLs. If, for example, your home page can be reached in multiple ways – for instance, http://example.com/home, http://home.example.com, or http://www.example.com – it's a good idea to pick one of those URLs as your preferred (canonical) destination, and use 301 redirects to send traffic from the other URLs to your preferred URL.You're merging two websites and want to make sure that links to outdated URLs are redirected to the correct pages.Broken pages (404)Fixing the duplicate content issuesWhen Not to Use 301 Redirects Do not use the 301 redirects if you might ever consider publishing the original URL again. Examples of use cases for the 301 redirect.Seasonal products on ecommerce sitesProducts are temporarily out of stockTemporary special offer landing pagesThe other examplesGeotargetingA/B testingDevice Targeting How 301 Redirects Impact SEO301 redirects can actually aid SEO, as the redirect will forward practically all of the original page’s PageRank to the new one. This means that, after the redirect, the new page will have about the same authority as the original content that you’ve redirected. How to Implement the 301 RedirectThe easiest way is by specifying the redirect in the .htaccess file in the server’s root folder. You can write the code in two ways, as pictured below:301 Redirect PillarThe first part defines the redirect (“Redirect 301” or “RedirectPermanent”). You follow it by the slug of the old URL you are redirecting from. Since the command resides in the root server of that domain, there is no need to include the full URL here.The final element is the full URL of the redirect destination.Note that although you might be redirecting pages on the same domain, you must provide the full URL for the destination. 302 REDIRECT – MOVED TEMPORARILY This redirect helps forward traffic to a new URL only temporarily. You should use it whenever you need to block user access to a particular page for a limited time. The “302” status code in its name indicates that the file (a document or a web page) has temporarily moved to another URL.When to Use 302 RedirectsYou should forward URLs with the 302 redirects only when the original destination becomes inaccessible for a limited time, and you will want to make it live again. The most common examples of such situations include:GeotargetingA/B testingDevice Targeting (When you have a desktop and mobile website, and you want to redirect desktop visitors that come to the mobile website, and vice versa.)Redirecting product pages that are temporarily out of stock or special offers pages.When Not to Use 302 RedirectsIf you know that the page has moved to a new URL permanently. In such a case, use the 301 redirects we described above.How to Implement the 302 RedirectThe 302 Redirect works almost identically to its permanent counterpart, and its code differs only in the response code you use to describe it. For example:ScreenshotNote the “302” response code instead of the 301 we used to redirect a URL permanently. How 302 Redirects Impact SEOBecause the 302 redirect is temporary, it does not pass page authority from the old URL to the new URL. This means that the new URL will not inhibit the original file’s authority or links, and search engines will always consider it separate from it.303 REDIRECT – SEE OTHERThe 303 Redirect works similarly to the 302 temporary redirects. It tells the browser (and the search engine) that the resource it tried to access has been replaced with another one. There is one difference between the two, though. The 303 redirect is not cacheable, meaning that the search engine will not include it in its cache. This is important if you might be changing destination targets for the redirect, and don’t want any of those pages to get cached by Google.When to Use 303 RedirectsThe use cases for the 303 Redirect are almost identical to the 302. However, as stated above, if you plan to change the target for the redirect during the temporary redirect, the 303 method is better suited.When Not to Use 303 RedirectsAgain, just like with the 302 redirects, 303 should never be used for permanent redirects.How 303 Redirects Impact SEOThe 303 Redirect has absolutely no impact on SEO, in fact. It does not forward page authority or links to the new URL and it is not cacheable by the search engine.307 REDIRECT – MOVED TEMPORARILY307 is another temporary redirect that differs from similar methods above by the way it is executed. Webmasters often use it instead of the 302 redirects if the request method cannot be changed for the destination URL.In most cases, this means that the traditional GET method must be replaced by the POST one when initiating the redirect.When to Use 307 RedirectsTypically, the 307 redirects are used in conjunction with a form action that requires specific POST redirect.When Not to Use 307 RedirectsJust like any other temporary redirect, the 307 should never be used when forwarding traffic from one URL to another permanently.How 307 Redirects Impact SEOThe 307 redirect has no impact on SEO.308 REDIRECT – PERMANENT REDIRECTThis is the permanent counterpart of the 307 redirects. The 308 redirect forces the request method to be the same as the original request.When to Use 308 RedirectsThis redirect method works particularly well when a company is moving a very complex website with a lot of forms with the POST method.When Not to Use 308 RedirectsThe 308 redirect is the wrong choice for all occasions in which cacheability can lead to unexpected negative behavior.Part 2. Client-Side RedirectsUnlike server-side redirects, these options do not execute on the server-level but happen in the browser as it tries to access a specific file. In general, the client-side redirects work when a webmaster has no ability to set up or control the server behavior. A good example of this is not being able to access the .htaccess file on the server to specify the redirect.There are some drawbacks of this type of redirects for SEO. Namely, not all browsers support these redirects, and might not redirect the user correctly. Also, search engines may not pass the page authority from the original content to the redirected page.Finally, client-side redirects break the back button, often looping visitors to the URL they were redirected to. There are two main types of client-side redirects:META REFRESH REDIRECTThe Meta Refresh redirect resides in the section of the file you want to redirect, and forwards the browser to another destination when it is trying to access it. It’s used to instruct a browser to refresh a page or load another URL after a certain number of seconds.The redirect code looks like this meta HTTP-equiv="refresh" content="0; url=http://domain.com/other-url/" One notable use case for those redirects was to push users to doorway pages containing different, often commercial in nature, content than the page the person thought they were going to see. It’s worth noting that such practices are against Google’s guidelines. Moreover, the search engine doesn’t recommend this redirect type for two reasons:User Experience – Although the user never sees the original page as the redirect executes before they have a chance to, the file will reside in their browser history.Processing time – for the redirect to work, the browser must parse the original URL, extract the redirect and initiate it before the person can see the forwarded page.JAVASCRIPT REDIRECTSJavaScript redirects work similarly to the Meta Refresh method, although they require the client (a browser) to process JavaScript to access the destination URL. The JavaScript redirect code resides in the section of the HTML file as well, and looks like this:When to Use JavaScript RedirectsThe two most common use cases for JavaScript redirects include redirects based on user interaction or device targeting, where the redirect detects a specific device and forwards a person to a page optimized for it. Using JavaScript to redirect users can be a legitimate practice. For example, if you redirect users to an internal page once they’re logged in, you can use JavaScript to do so. When examining JavaScript or other redirect methods to ensure your site adheres to Google guidelines, consider the intent.Keep in mind that 301 redirects are best when moving your site, but you could use a JavaScript redirect for this purpose if you don’t have access to your website’s server.THE IMPACT OF CLIENT-SIDE REDIRECTS ON SEOThe major downside to client-side redirects is the fact that they do not provide any information about the reason for the redirect. This, in turn, makes it harder for search engines to treat the redirect, also from the SEO perspective.

img"Knowing which URL redirect to implement on your site will prevent future obstacles that can negatively impact your site's performance."KALPESH GUARD | CFO and CoFounder, seoClarity

URL Redirect Use CasesNeither of the redirects we described above is a typical SEO strategy. It doesn’t mean, however, that SEOs wouldn’t use redirects in their strategies. And so, below, you’ll find some of the most common use cases when SEOs implement or at least are heavily involved in the set up of the redirects.Use Case #1: Relaunching a new website/Website MigrationSEO Pricing v1.0__Software_croppedIf you’ve gone through a website migration before, then you know how challenging the process can be from both a technical and SEO point of view.Much can go wrong, and if it does, the most common result for you is a loss of rankings, traffic, and conversions. Need some help with your migration? Consider our website migration services for the assistance you need to come out ahead. Setting up correct redirects helps ensure that none of the above happens because Google can index the new site, understands the relationship between old and new content, and passes the link juice from the former to the latter. The most common scenarios for using redirects in a website migration project include:Moving the site to SSL and migrating URLs from HTTP to HTTPS.Migrating the old separate mobile site to responsive pages.Moving to a new domain. Updating and reworking the site’s architecture.Changing the URL structure of sections on the site. Replacing old pages with new content assets, and more.The most common redirect types used in these scenarios are 301 Permanent and 302 Temporary, depending on the nature of the redirect.Use Case #2: GEO-location RedirectsMany global organizations want to display location-relevant content to visitors from their target markets. In such cases, launching GEO-location redirects helps to automatically serve the appropriate content to users depending on their location and/or language settings. However, there are few things worth remembering when using Geo-location redirects. First of all, Google advises not to redirect based on the user’s IP address.It can confuse its crawler too, and cause problems with indexing your content. Instead, the search engine recommends using ccTLD and Google Search Console settings to target international users. In this case, the most common redirect type is the 302 Temporary. A website can also serve the right content dynamically. Use Case #3: Device TargetingA common redirect on websites with a separate mobile site. The redirect detects the type of a device a person uses to access the site and redirects them to the appropriate version, mobile or desktop. Google recommends two implementations of this redirect – HTTP redirects and JavaScript redirects. Use Case #4: Redirects for PPC/Affiliate Marketing CampaignsIn some PPC or affiliate marketing campaigns, marketers prefer to specify redirects to the original landing page, rather than use the direct URL. In the case of affiliate marketing, it might generate many references to the URL online.However, because of the nature of the affiliate agreement, Google might perceive those as bought links and penalize the site for not following the webmaster guidelines. A temporary, non-cacheable redirect helps to protect the site from such a penalty while still allowing the traffic to arrive at the target URL. Use Case #5. Redirects for A/B TestingWhen testing different variations of a page, the company must also use a temporary redirect that will forward some visitors to the alternative page to test its impact.For these redirects, we recommend using temporary, non-cacheable redirects to prevent the alternative version to get cached, indexed and used to rank the original content. As a matter of fact, Google recommends using the 302 redirect for this type of testing as well.

Common SEO Mistakes When Implementing RedirectsWe’ve covered quite a lot of theory regarding redirects and how they can affect an SEO strategy. You know what redirects are, how they work, and when to use them and how. So, let us show you the most common mistakes SEOs make when implementing them in their projects.Mistake #1: Moving Domains without Setting Up the Redirect FirstUnfortunately, we see this happening too often. A company decides to migrate the website to a new domain, gets the new site ready, launches it and… hands the rest over to the SEO, expecting the traffic levels to continue as before. The problem?During the transition period, the new domain might have gotten crawled and indexed already. Because there haven’t been any redirects in place, Google now sees it as a duplicate of the old domain, and might, potentially, even penalize it for that. To avoid that, have all the redirects set up before the new site goes live. Then, submit the new site to Google’s index via the Google Search Console and let the search engine follow and understand those redirects by itself.Mistake #2: Redirecting to a Non-Relevant URLFor SEO purposes, the topical relevance is critical for a redirect to work. Redirecting to a random page will, most likely, have no effect on your SEO.Failing to understand the connection between the two pages, Google might not pass the link authority between the two, reducing the redirect’s positive impact on SEO.As a rule, when redirecting, always forward traffic to the closest, most relevant alternative to the original page.Mistake #3: Setting Up Redirect ChainsThis is a common scenario. You create a newer version of a page and redirect the old one to it. But then, you create another version and set up another redirect and so on.Over time, what used to be a single redirect becomes a chain of three, four or more redirects. Now, it makes little difference for your users, they never see the many jumps from the original page to the target destination. But Google does.As a matter of fact, the search engine’s crawler might stop following the chain after two redirects, resulting in never accessing the newest page. Error Redirect PillarStatus Code Redirect PillarMistake #4: Increasing Redirect LatencyAnother downside of having too many redirects is higher latency that can affect the user experience. Remember that each redirect is a server request that needs to be processed.On slower connections, this might result in longer page load time for a user. Similarly, multiple redirects may trigger the “too many redirects error,” preventing the person from ever reaching the end of the chain.Mistake #5: Redirects URL within Sitemap/internal LinksTechnically, it’s not a problem if a large portion of your site redirects somewhere else. Having said that, having such a situation could have an effect on the crawlability of your website.Search engine crawlers have a limited time to go through all your content – the Crawl Budget. Redirects may push them off the path and use up the budget for unnecessary redirect jumps, instead of evaluating the content that matters.As a best practice, when moving pages you should implement 301 redirects from the previous URLs to the new ones and keep them active for at least 1 year.Mistake #6: Having Existing Redirects During the Site MigrationWe’ve talked already about the importance of having redirects set up right away during the migration project. However, a common mistake here is not to consider any existing redirects that are already in place on the old site.These redirects from previous migrations or updates catch older URLs linked on external websites or bookmarked by users.If older redirects are simply removed, these external links and bookmarks will lead to 404s (or worse, HTTP 500 server errors depending on how these old pages are handled).If these old redirects are kept as they are, and new redirects added without any consolidation with these existing redirects, and this creates redirect chains we’ve talked about above.Old redirect: older-page-A→ current-page-BNew redirect: current-page-B → new-page-CWhile we could plan to have A → CTo avoid this, reassess existing redirects as a whole and consolidate them to reduce any potential chains.

Best Practices for SEO RedirectsFor the end, let us offer you some of the best practices for setting up SEO redirects. Follow these strategies, and you’re unlikely to encounter any problems with your redirects.#1. Redirect to the Preferred Version of the Website URLWhen setting up redirects, always target the most relevant and preferred version of the target URL. This is particularly important when the website generates URLs dynamically, and can have multiple URLs for the same page.#2. Redirect to Relevant Alternate URLWe’ve covered this issue already. However, given its importance, it’s worth recapping it again. Always redirect to the most relevant alternative to the original URL to retain topical relevance.#3. Avoid Redirect ChainsDo not set up more than two simultaneous redirects. If possible, reassess your redirects and consolidate them to eliminate the chain.#4. Clean Up RedirectsRedirects are something you often set and forget. But the site changes constantly and old redirects might need reevaluating. Perhaps some temporary redirects are not needed anymore and can be lifted or changed to permanent to forward the link equity between the two URLs, finally.#5. Remove Redirects URL Within Sitemap/Update Internal Links As a rule, the sitemap should not include redirected content. Instead, it should only list the final, target URLs for each redirect. Evaluate your sitemap regularly, particularly if its created automatically by your CMS system, to identify redirects to remove and replace with live URLs.

URL Redirects With seoClarityseoClarity's Site Audit technology offers insights into all URL redirects along with your associated URLs throughout the platform. Here's a screenshot from the platform that offers the detail on the number of redirects and how many redirect paths the pages have. RedirectScreenshotseoClarity is also unique in displaying associated URLs within the platform so you can report on your site analytics and rankings by page and associated pages.This issue comes up when you have URLs from the previous year which are now redirected to the new URLs.In your reporting, seoClarity allows the previous URL to be associated with the new URL so you can easily report, analyze, and discover opportunities or losses quickly at the URL level.

Frequently Asked QuestionsCan I have too many 301 redirects?Yes! If you’re talking about redirecting a single URL multiple times.Do redirects hurt the crawl budget?They can. Each redirect causes the search engine to issue another request to find the requested document. As a result, if redirects add up, they will affect your crawl budget usage.When crawl budget is consumed largely by redirects, more relevant parts of the site may get crawled less often or not at all.Does Google crawl and index redirects?No, it does not. This means that if you redirect from one page to another, the content on the original page will not get indexed. Only the target URL will be crawled and indexed by the search engine. How long should you keep a 301 redirect?The 301 redirect is permanent, therefore, it should never be lifted. Google’s John Mueller confirmed that permanent redirects should remain live for a very long time.The reason for that is that it can take Google anything from 6 months to a year to completely recognize that a site or page has moved.When does Google treat 301s as “soft 404s”?Google’s John Mueller confirmed, if you 301 redirect pages that should 404 to your home page, Google will treat them as soft 404s anyway and thus all you are doing is confusing your end users.There is no benefit in using a 301 redirect for a page that you killed off when you are redirecting it to a page that is not relevant to that 404 page.You should only 301 redirect pages to other pages that have a one to one relationship and not ones that are unrelated. So if you have a page about apples and you decide to get rid of it, redirecting your apple page to your home page is not useful.How long does it take Google to recognize a 301 redirect?As John Mueller from Google confirmed, that 301 redirects applied to permanent site move situations should be active for a long time.He explained that it takes at least six months to roughly a year for Google to be able to completely recognize that your site was moved.What is a sneaky redirect and why is it bad for SEO?A sneaky redirect aims to deceive the search engine crawlers by displaying different content than what human visitors see.However, redirecting users to one content and showing a different one to the search engine is a direct violation of the Webmaster Guidelines and can result in a penalty.Do All 301 Redirects Pass 100% PageRank?No, according to Google, 301 redirects cannot always pass all PageRank between URLs. Each redirect loses a tiny bit of the original PageRank.How Does Google Assign PageRank through 301s?The search engine uses redirects to pick the canonical URL for the page. By doing it this way, Google can focus on all the signals that go to those URLs to the canonical URL.When should you choose the canonical vs 301 redirects?Redirects help forward visitors from a URL that will, temporarily or permanently, no longer exist to its active counterpart. Canonicals, on the other hand, work best when having similar or duplicate content live on the web.In such an instance, canonical helps to notify the search engine about which version of the content is original and should be indexed.

Redirect to URL –

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>

+++++++++++++

<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>

+++++++++++++

state = { redirect: null };

render() {
  if (this.state.redirect) {
    return <Redirect to={this.state.redirect} />
  }
  return(
  // Your Code goes here
  )
}

// update the redirect
 this.setState({ redirect: "/someRoute" });
 
 
 +++++++++
 
 
 

 

 

 

https://blog.pshrmn.com/single-page-applications-and-the-server/

Single-Page Applications and the Server

SPAs run on the client, but still need a server. A brief overview of SPA deployment options.

April 16, 2018

Single-page applications (SPAs) are distinguished from regular applications because they do not need to make server requests when the user navigates. However, the application still needs a server to provide the initial files for the application to render. How Single-Page Applications Work covers the client-side aspect of how this works and here we will cover how different types of servers can support single-page applications.

Server Types

Websites are backed by two types of servers: web and application. NGINX, a web server, provides a good explanation of the two. The most general way to differentiate the two is to say that a web server serves static content (i.e. files that already exist on the server) while an application server can generate new content.

With single-page applications, there are three main scenarios for serving the application’s content:

  1. Purely static
  2. Configurable static
  3. Dynamic
Purely Static

A purely static web server can only successfully respond to requests if a resource at the requested location exists. This will typically be the case when you are using a static host, such as GitHub Pages or Amazon S3.

With a purely static server, a request for /horses.html only succeeds (returns a response with status 200) if the server’s root directory contains a horses.html file. If the resource does not exist, the server will return a 404 response.

Configurable Static

A web server can be configured to respond with an alternative file if the requested resource doesn’t actually exist on the disk. If a request for /bears comes in and the server has no bears file, the configuration can tell it to respond with an index.html file instead.

Dynamic

An application server will have a web framework running on top of it. For example, a Node application server might be running Express and a Unicorn application server may be used to run Ruby on Rails.

The framework is able to match requests and dynamically generate responses. Like a configurable static setup, requests don’t have to map directly to files on the server, but a dynamic setup gives you even more leeway.

An application server is most likely run as a proxy of a web server, but the web server would typically just pass non-static requests to the application server.

Generally speaking, a dynamic/configurable static server is preferable for running a single-page application. If you are using a static file host, you can still run a single-page application, but there are some limitations that you will need to know.

Serving Single-Page Applications From Static File Hosts

If you are running a single-page application through a static file host, you have two options.

The first, and simplest, is to have a single HTML file. With this system, the URL’s hash will be used to store location data.

This would be the home page:

https://example.com/#/

and this is the contact page:

https://example.com/#/contact

Because the location is stored in the URL’s hash, and the server only uses the location’s pathname to map resources, all requests to the server for pages in the application will be for the root index.html file.

Most single-page application routers should provide you with a way to encode locations in the hash. With the Curi router, this is done using the Hickory hash history.

import { hash } from "@hickory/hash";
// ...
const router = curi(hash, routes);
// current URL: "example.com/#/"
router.navigate({ url: "/contact" });
// changes the URL to "example.com/#/contact"

The popular history package also has a hash option.

import { createHashHistory } from "history";
const history = createHashHistory();

A visual drawback of using hash URLs is that they are a bit ugly.

An alternative approach is to generate HTML files for each page in the application. There are a number of tools that can assist you in doing this. Curi provides a @curi/static package for generating static pages. Other tools include React Static, GatsbyJS, and VuePress.

Many static file hosts allow you to set a "fallback" page to serve when there is a request for a page that you haven't generated content for. This allows the site to work without generating the content for every single possible URL, which is especially handy if you have pages that should always be generated on the client side.

Serving Single-Page Applications from Configurable Static Servers

If you can configure your web server, creating a single-page application with “pretty” URLs is much easier.

The basic gist of how to configure a web server for single-page applications is that you have a single HTML file that your application serves for almost every request.

<!-- index.html -->
<!doctype html>
<html>
  <head>...</head>
  <body>
    <div id="root"></div>
    <script src="/static/js/index.js"></script>
  </body>
</html>

Request for /camels? Respond with index.html. Request for /badgers? Respond with index.html. Request for /static/js/index.js? That is where the “almost” comes in. The server needs to distinguish between requests for HTML content for requests for other files so that it can serve the correct files, and not the index.html file, for those requests.

With the Apache web server, you can use mod_rewrite to try to respond with the requested file, but fall back to responding with a default HTML file when the resource does not exist.

RewriteEngine On
# set the base URL prefix
RewriteBase /
# for requests for index.html, just respond with the file
RewriteRule ^index.html$ - [L]
# if requested path is not a valid filename, continue rewrite
RewriteCond %{REQUEST_FILENAME} !-f
# if requested path is not a valid directory, continue rewrite
RewriteCond %{REQUEST_FILENAME} !-d
# if you have continue to here, respond with index.html
RewriteRule . /index.html [L]

With Nginx, you can use try_files to serve the HTML file. This will attempt to serve the file at the provided $uri, but if that does not exist, it will fall back to the index.html file.

server {
  ...
  location / {
    try_files $uri /index.html;
  }
}

Note: These configurations are gleaned from an old React Router documentation. If you have issues getting these Apache/NGINX setups to work, I would recommend either checking their respective documentation or StackOverflow.

Dynamically Serving Single-Page Applications with Application Servers

The setup for application servers is similar to configurable static servers. In some cases, they may even overlap by having Apache/NGINX/etc. serve static files and pass other requests to a proxy, the application server.

There are so many different application servers out there, that it is impractical to cover the setup for each of them here, but the gist is always the same: process the request, determine how to respond, and respond with some HTML. The example code below will use the Express framework.

An application server needs to identify static resource requests and respond with the correct file. If you configure your web server to handle these, then you can skip this on the application server. Additionally, a dynamic server needs to identify API requests so that they can be handled properly.

Some single-page applications will also employ server-side rendering. Instead of using a common HTML file, server-side rendering will respond with the fully structured HTML for the requested page. Some people swear by this, while others consider it unnecessary. At the very least, there are some caveats to it, but we will come back to this in a little bit.

Your framework should provide a way to identify static resource requests. This basically entails specifying a static file directory so that any request whose pathname begins with the static directory will just serve the requested file (or fail with a 404 response if the requested file does not exist).

To do this with Express, you would use its static() method and your Express app’s use() method. static() receives the local directory where the static files exist. You can either pass this as the only argument to use(), in which case it will respond to requests for the same local directory, or you can pass it a first argument path if static file requests don’t refer to the literal location.

const express = require("express");
const app = new express();

// requests for /public/js/index.js
// will return public/js/index.js
app.use(express.static("public"));

// requests for /static/js/index.js
// will return public/js/index.js
app.use("/static", express.static("public"));
app.listen("8000");

Frameworks also need to know how to map requests to to how they should respond, similar to how routes work in a single-page application. When the framework gets a request, it will iterate over these handlers and use the first one that matches the request to respond.

In order for the framework to respond to any possible location, we need to give it a catch-all route handler that responds with the common HTML file.

const path = require("path");
app.use("*", function(req, resp) {
  resp.sendFile("/public/index.html");
});

The order of operations is important here. A catch-all route will match every location, so anything that shouldn’t be matched by it (i.e. static file and API requests) needs to be defined prior to the catch-all route.

// 1. match static files
app.use("/static", express.static("public"));
// 2. match API requests
app.use("/graphql", ...);
// 3. finally, match everything else
app.use("*", function(req, resp) {
  resp.sendFile("/public/index.html");
});
Server-Side Rendering

The technique outlines above sends a minimal HTML file, which will be “filled in” on the client-side to render the application. Server-side rendering (SSR) allows you to render each route’s HTML content on the server. The response will then be an HTML file that is already “filled in”.

Server-side rendering also only really makes sense to attempt if you are running a Node server because you can re-use client-side code on the server. Technically speaking, if you aren’t using Node, you could create the same UI for whatever framework your server uses, but that would require you to duplicate your render logic.

The advantages of using SSR is that your application will have a faster initial render for users and that it is easier for search engines to crawl your content. Whether an application really benefits has a variety of factors. For example, if you are using server-side rendering for search engine optimization, only public pages need to be server-side rendered. A private page page (one that is only visible to authorized users) would not benefit from server-side rendering since no search engines should attempt to index it.

Instead of returning an HTML file from the disk, server-side rendering will generate an HTML string when a request comes in. There are two parts to this HTML string: the base HTML and the route specific HTML.

The base HTML is a template that will be used for all requests. This should include any <script> tags that will be necessary for running the application on the client. The route specific HTML will be inserted into the template. Most of this should be inserted into a container element in the <body> of the template, but you may also want to insert elements into the <head>>, such as a <title>.

The technique for rendering on the server will depend entirely on how you are rendering on the client. If you are using React, the react-dom package provides server methods for generating an HTML string.

Note: If you do server-side rendering using React, on the client you will want to use ReactDOM.hydrate() instead of ReactDOM.render().

function responseHTML(content) {
  return `<!doctype html>
    <html>
      <head></head>
      <body>
        <div id="root">${content}</div>
        <script src="/static/js/bundle.js"></script>
      </body>
    </html>`;
}

Important! Any static resource references in the template should be absolute. If you use a relative path (static/js/bundle.js) in the template, requests for nested URLs (/parent/child) would attempt to load non-existent resource URLs (/parent/static/js/bundle.js).

When the application just sends the same HTML file for every request, it doesn’t matter what the requested path is, but with server-side rendering it is important to render based on the request URL.

Note: With Express, the request object can be referenced to get the requested path. req.path, which is the requested URL’s pathname, can be used to determine the route that matches. However, if the app renders content using the search/hash, req.url should be used.

To demo the actual rendering, we will use React and Curi, which makes server-side rendering very easy.

import React from "react";
import renderToString from "react-dom/server";
import { createRouter } from "@curi/router";
import { createReusable} from "@hickory/in-memory";
import { createRouterComponent } from "@curi/react-dom";

import routes from "../client/routes";
import App from "../client/components/App";

// 1. Create a reusable history instance for all renders
const reusable = createReusable();

app.use("*", function(req, resp) {
  // 2. Use the request's URL to create the router.
  // Curi will use the provided location to generate
  // a response object
  const router = createRouter(reusable, routes, {
    history: {
      location: req.url
    }
  });
  const Router = createRouterComponent(router);

  // 3. Render the application using React.
  const content = renderToString(
    <Router>
      <App />
    </Router>
  );

  // 4. Insert the content into the template.
  // We want to return the entire page's HTML, not just
  // the content rendered by React
  const html = responseHTML(content);

  // 5. Send the response HTML.
  resp.send(html);
});

That is the general gist of server-side rendering. Actual implementations vary by framework and router, but the idea is always the same.

Recap

If you are using a static file host, you will either need to use hash routing and a shared HTML file or generate an HTML file for every possible route in your application.

Web servers can be made more amenable to single-page applications if you can configure them. This allows you to respond with an HTML file for requests that don’t have a matching resource on the server.

Application servers make serving single-page applications easy by using catch-all routes to respond to requests for any location. It is important that these match any other possible URLs, such as static resource and API requests, first so that the catch-all doesn’t catch those. If your application server is running Node, you can take advantage of server-side rendering to pre-generate the page’s HTML content, but this isn’t always necessary.

 

https://reach.tech/router/server-config

Server Configuration

If your app works fine until you hit “reload” or manually type in a URL and then get a 404 error, then your server is not configured correctly.

Whether you are server-rendering or not, all apps using Reach Router need to be configured to deliver the same JavaScript code at every URL.

For non-server rendered apps, we recommend develping with create react app, and for your production file server we recommend serve.

If you can’t use either of these tools, you will need to learn how to configure your server to serve your index.html file at every url.

Here’s an example in express:

const path = require("path")
const express = require("express")
const app = new express()

// requests for static files in the "public" directory
// like JavaScript, CSS, images will be served
app.use(express.static("public"))

// Every other request will send the index.html file that
// contains your application
app.use("*", function(req, resp) {
  resp.sendFile("/public/index.html")
})

app.listen("8000")

Paul Sherman has written an in-depth article about this, if you’re still unclear we recommend you give it a read: Single-Page Applications and the Server

 

https://reach.tech/router/server-rendering

Server Rendering

If server rendering is a new concept to you, it’s important to grasp the big picture of how all the pieces of server rendering fit together before diving into the details.

  • 1. A user types your URL into their web browser and hits enter
  • 2. Your server sees there is a GET request
  • 3. The server renders your React app to an HTML string, wraps it inside of a standard HTML doc (DOCTYPE and all), and sends the whole thing back as a responseSSR response
  • 4. The browser sees it got an HTML document back from the server and its rendering engine goes to work rendering the page
  • 5. Once done, the page is viewable and the browser starts downloading any <script>s located in the documentSSR waterfall
  • 6. Once the scripts are downloaded, React takes over and the page becomes interactive

Notice that with server rendering, the response the browser gets from the server is raw HTML that is immediately ready to be rendered. This is the opposite of what happens with regular client-side rendering which just spits back a blank HTML document with a JavaScript bundle.

By sending back a finished HTML document, the browser is able to show the user some UI immediately without having to wait for the JavaScript the finish downloading.

Now that you get the big picture, you’re probably ready to add server rendering to your React app. Unfortunately, that process is way too long to include here. Instead, check out the full post below – all 14 minutes worth.

 

Want more?

For a much more comprehensive explanation, visit Server Rendering with React and React Router.

 

Server Rendering

There are a few things to consider when server rendering your React app with Reach Router.

  • Transpiling JSX for Node.js
  • Providing the location statically to the app
  • Handling redirects
  • Data loading

Transpiling JSX for Node.js

We aren’t going to get into this, but we welcome PRs with links to documentation/tutorials that do.

Providing the Location

This part is pretty simple, bring in ServerLocation and wrap your app in it. Whether you’re using express or something else in Node, you’ll have a req object somewhere with a url property. That’s what we need.

import { renderToString } from "react-dom/server"
import { ServerLocation } from "@reach/router"
import App from "./App"

createServer((req, res) => {
  const markup = renderToString(
    <ServerLocation url={req.url}>
      <App />
    </ServerLocation>
  )
})

And that’s it. Instead of listening to a browser history, the routers inside the app will match against the url you provided.

Handling Redirects

When you render a <Redirect/> a redirect request is thrown, preventing react from rendering the whole tree when we don’t want to do that work anyway.

To handle redirects on the server, catch them, then redirect on the server.

import { renderToString } from "react-dom/server"
import {
  ServerLocation,
  isRedirect
} from "@reach/router"
import App from "./App"

createServer((req, res) => {
  let markup
  try {
    markup = renderToString(
      <ServerLocation url={req.url}>
        <App />
      </ServerLocation>
    )
  } catch (error) {
    if (isRedirect(error)) {
      res.redirect(error.uri)
    } else {
      // carry on as usual
    }
  }
})

Data Loading

When React Suspense ships, these docs will be updated with some great examples of server rendering with data loading. Until then, you’ll need to come up with your own strategy.

 

https://linchpinseo.com/htaccess-rules/

 

In this article, we’ll cover:

1) What is an Htaccess file?

2) Common 301 Redirect Htaccess Rules

There are common htaccess 301 redirect rules that I find myself searching for each time I build a website, redirect a page for an SEO strategy for a client, or help with a website’s SEO transition plan. So I thought I would create a resource where I could gather all the common rules into one spot to save me time for each project.

What is an Htaccess file?

The .htaccess, or Hypertext Access file, is a configuration text file that controls the directory and any subdirectories located on an Apache webserver. If you use a Linux-based web hosting plan, your web properties likely run on Apache. You may have seen the .htaccess file in certain directories, particularly if you have deployed WordPress, Shopify, Craft, or any other content management web software.

The .htaccess file can include specific instructions to the server. This file can configure the server to require a password for the directory where it resides. The .htaccess file can also be configured to automatically redirect users to another index file or site, restrict or allow users based on IP addresses, and disable directory listings. You may never need to edit the .htaccess file, but if you do, you must make sure that the file is named ‘.htaccess’ only, with the period in front and no .txt or .htm file extension.

Common 301 Redirect Htaccess Rules

Redirect a single page

Redirect 301 /pagename.php http://www.domain.com/pagename.html

Redirect an entire site or domain to a new one

Redirect 301 / http://www.domain.com/

Redirect an entire site to a subfolder

Redirect 301 / http://www.domain.com/subfolder/

Redirect a subfolder to a different website

Redirect 301 /subfolder http://www.domain.com/

Redirect a file extension but retain the page name

Example: If you want a .html extension to use the same filename but use the .php extension.

RedirectMatch 301 (.*)\.html$ http://www.domain.com$1.php

Redirect from an old domain to a new domain

RewriteEngine onRewriteBase /RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

Redirect from a non-www to a www subdomain

RewriteEngine onRewriteBase /rewritecond %{http_host} ^domain.com [nc]rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]

Redirect a domain to a www location with a subdirectory

RewriteEngine onRewriteBase /RewriteCond %{HTTP_HOST} domain.com [NC]RewriteRule ^(.*)$ http://www.domain.com/directory/index.html [R=301,NC]

Redirect from an old domain to a new domain that includes the full path and query string

Options +FollowSymLinksRewriteEngine OnRewriteRule ^(.*) http://www.newdomain.com%{REQUEST_URI} [R=302,NC]

Redirect from an old domain with a subdirectory to a new domain without the subdirectory but include the full path and query string

Options +FollowSymLinksRewriteEngine OnRewriteCond %{REQUEST_URI} ^/subdirname/(.*)$RewriteRule ^(.*) http://www.katcode.com/%1 [R=302,NC]

Redirect URLs with query parameters with files placed in a root directory

Example: The original URL being http://www.website.com/index.php?id=3 and the new URL being http://www.website.com/path-to-new-location/

RewriteEngine onRewriteCond %{QUERY_STRING} id=3RewriteRule ^index\.php$ /path-to-new-location/? [L,R=301]

Redirect URLs with query parameters and place files in a subdirectory

Example: The original URL being http://www.website.com/sub-dir/index.php?id=3 and the new page being http://www.website.com/path-to-new-location/

RewriteEngine onRewriteCond %{QUERY_STRING} id=3RewriteRule ^sub-dir/index\.php$ /path-to-new-location/? [L,R=301]

Redirect a site to HTTPS from HTTP to eliminate duplicate content

RewriteEngine onRewriteCond %{HTTPS} onRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Redirect a site from HTTP to HTTPS to eliminate duplicate content

RewriteEngine OnRewriteCond %{HTTPS} onRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

Remove an index.html or index.php and redirect to the root

RewriteEngine OnRewriteCond %{THE_REQUEST} /index.php HTTP [NC]RewriteRule (.*)index.php$ /$1 [R=301,L]
RewriteEngine OnRewriteCond %{THE_REQUEST} /index.html HTTP [NC]RewriteRule (.*)index.html$ /$1 [R=301,L]

Redirect URLs with query parameters to a directory-based structure while retaining the query string in the URL root level

Example: The original URL being http://www.website.com/index.php?id=100 and the new page being http://www.website.com/100/

RewriteEngine OnRewriteRule ^([^/d]+)/?$ index.php?id=$1 [QSA]

Rewrite URLs with a query parameter to a directory-based structure while retaining query string parameters in the URL subdirectory

Example: The original URL is http://www.website.com/index.php?category=fish and the new page being http://www.website.com/category/fish/

RewriteEngine OnRewriteRule ^/?category/([^/d]+)/?$ index.php?category=$1 [L,QSA]

Redirect an old website to a new domain and retain the URL path

RewriteEngine onRewriteCond %{HTTP_HOST} ^example-old\.com$ [NC]RewriteRule ^(.*)$ http://www.example-new.com/$1 [R=301,L]If you do not want to pass the path to the new domain, change the last line to:RewriteRule ^(.*)$ http://www.example-new.com/ [R=301,L]

Add a trailing slash to URLs without one

RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ http://www.example.com/$1/ [R=301,L]

Redirect from a blog subdomain to a blog folder

Example: Redirect blog.oldsite.com to www.newsite.com/blog/

Options +FollowSymLinksRewriteEngine OnRewriteCond %{REQUEST_URI}/ blogRewriteRule ^(.*) http://www.somewhere.com/%{REQUEST_URI} [R=302,NC]RewriteRule ^(.*) http://www.somewhere.com/blog/%{REQUEST_URI} [R=302,NC]

Redirect one directory to another

Options +FollowSymLinks RewriteEngine On RewriteRule ^(.*)/old-directory/(.*)$ $1/new-directory/$2 [R,L]

Redirect if url contains specific string

writeCond %{REQUEST_URI} findthisstring
RewriteRule .* index.php

 

 

RewriteRule ^(.*)weekends-(.*)$ https://guerillaporn.com/weekends [L,R=301]

 

Scroll to Top